2
votes

This is indeed an assignment, but I am stuck, it may just be the wording that I am not getting.

Make a function with variable number of arguments that searches the rest of the arguments for a sub-string provided as the first argument. This function will return a vector containing all arguments that contain the sub-string

This is what I have so far:

#include <iostream>
#include <string>
#include <algorithm>
#include <stdarg.h>
#include <vector>
using namespace std;

vector<string> search(string str, ...);

int main (){
    va_list arguments;
    char contin = 'y';
    string str;

    va_start(arguments, str);
    cout << "Enter a string that will be searched for in the rest of the strings: ";
    str += va_arg(arguments, str);
    while(contin == 'y'){
        cout << "Enter a string that will be searched in: ";
        str += va_arg(arguments, str);
        cout << endl << "Enter \''y\'' to continue or \''n\'' to end to start seach:" << endl;
        cin >> contin;
    }
    va_end(arguments);
    search(arguments);
  return 0;
}

vector<string> search(string str, ... ){
    va_list containing;
    va_start (containing, str);
    if (std::find(str.begin(), str.end(), str.front()) != str.end()){
        str += va_arg(containing, str);
    }

    return containing;
}

I get these errors: Line 37: "str += va_arg(containing, str);" -error C2059: syntax error : ')'

Line 40: "return containing;" - error C2664: 'std::vector<_Ty>::vector(const std::vector<_Ty> &)' : cannot convert parameter 1 from 'va_list' to 'const std::vector<_Ty> &'

Line 36: "if (std::find(str.begin(), str.end(), str.front()) != str.end()){" - error C2039: 'front' : is not a member of 'std::basic_string<_Elem,_Traits,_Ax>'

Line 21/24: "str += va_arg(arguments, str);" - error C2059: syntax error : ')'

Also, am I headed in the right direction or doing something completely wrong?

1
+1 for a very novel use of va_args. Here's a man who doesn't play by anyone's rules.Kerrek SB
va_args macros (va_list, va_start, va_end) are readonly. You can't write to it, as you do in mainMark Lakata

1 Answers

1
votes

There's definitely things you don't understand about functions with variable args.

Firstly to call a function with variable args you just use the normal method

search("here", "are", "some", "strings");

Secondly because the types of parameters to a variable arg function are unknown you are seriously restricted in the type of values you can call the function with. Any complex object like std::string is forbidden. Simple types like int, double and char * are OK.

Thirdly the second argument to the va_arg macro is the type of the value you wish to access e.g. va_arg(containing, char*).

I can only think that 'strings' in your assigment means the old-fashioned C type, i.e. const char * not std::string.