Question

I need to store each lines of a text document into a vector. However any file text I try, the output is always 2 lines. First one is empty and second one always output: "DONE". I'm on Windows7 X64, using VC++2013.

I have been trying to solve this for many hours. I tried many different approach but the result stay the same. I suspect that "DONE" is the return value from getline() however I don't understand with my code is not working like it should.

int main() {

    ifstream hFile("test.txt");

    vector<string> lines;
    string line;
    while (std::getline(hFile, line))
        lines.push_back(line);

    cout << lines[1];

    hFile.close();

    getchar();
    return 0;
}

EDIT: It works fine when executing the program from the compilation folder but not in the debug console of VC++...

Était-ce utile?

La solution

The program looks mostly correct. The only problem is that your code assumes that there are, at least, two lines in your file: if there are few lines, e.g., just one or the files couldn't be opened, the statement

cout << lines[1];

result in undefined behavior. Did you mean to print each line of the file rather than just the second line?

From the description of the behavior I would suspect that you file either contains the string DONE or you are actually executing a different program!

Autres conseils

Be careful, it proves nothing about the count of lines:

cout << lines[1];

Use line.size() to count the read lines. In fact for a file with one line, it's undefined behavior to access second item.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top