how to use <fstream>

Hi,

I am using <fstream> in my code and using it to accept string inputs from a text file. My code is as follows:

string instruction;
infile.open("words.txt");
while(!infile.eof())
{
infile >> instruction;
getline(infile, instruction);
cout << instruction << endl;
}

In the text file the first line is "A BC DEF". But when I use cout << instruction, only " BC DEF" is displayed, i.e. the first character is omitted. Is there an explanation for this?
infile >> instruction; reads a word from a file (a sequence of non-whitespace characters) and stores it in "instruction". In your case, it reads "A" and stores that.
getline(infile, instruction); reads what's left of the line and stores it in "instruction". In your case, it reads " BC DEF".

also, if you really run this with the input you described, " BC DEF" is displayed twice, It is becausewhile(!infile.eof()) is an error: this loop always reads past end of file. Correct input loop has the structure
1
2
3
4
while(cin >> instruction)
{
    cout << instruction << '\n';
}
or
1
2
3
4
while(getline(cin, instruction))
{
    cout << instruction << '\n';
}
depending on what you're after.
Topic archived. No new replies allowed.