-2

I'm creating a little program in order to test the vector class.
I'm using a string vector then i read a text file and i'm tring to write each word in the vector (1 word for each space).
When I try to use the push_back in order to put a string into the vector appear an error that says "There isn't a function to convert a string to a char".

If i made some english error sorry.
Thanks for the help.

I read some guide that explain how work the push_back but in all of this tutorial the use this declaration.

vector<string> v_of_string;<br/>
//allocate some memeory<br/>
v_of_string[1].pushback(string to punt in the vector);<br/>

My Code

int main() {
    vector<string> str; 
    //allocate some memory 
    ifstream iFile("test.txt"); 
    int i = 0;
    if (iFile.is_open()) {       
        while (!iFile.eof()) {
            string temp;
            iFile >> temp;
            str[i].push_back(temp);
            cout << str[i];
            i++;
        }

        iFile.close();
    }
return 0;
}
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52

1 Answers1

4

So

str[i].push_back(temp);

is an error, you meant

str.push_back(temp);

You push_back to the vector as a whole, not to one particular element of the vector, so there is no need for [i]. I expect if you go back to your guide then it will say the same.

You could also replace cout << str[i]; with cout << str.back(); to always output the last element of the vector. So actually you don't need the variable i at all.

Also

while (!iFile.eof()) {
    string temp;
    iFile >> temp;

is incorrect, it should be

string temp;
while (iFile >> temp) {

See here for an explanation. I'd be interested if you got this code from your guide as well. Using eof in a while loop in C++ must be single commonest error we see on stack overflow.

Incidentally str is a poor choice of name for a vector variable IMHO.

john
  • 85,011
  • 4
  • 57
  • 81