It so happens that you have only one thing per line of the file.
However, you could have more than one. Use getline().
myfile.txt
1 This is the first time
2 This is the second line
3 This is the third rhyme
4 This is the one to find
5 Out of the counting dime
myprog.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <fstream>
#include <iostream>
#include <string>
usingnamespace std;
constint LINE_TO_FIND = 4;
int main()
{
string line;
ifstream f( "myfile.txt" );
for (int i=0; i<LINE_TO_FIND;i++)
{
getline(f,line);
}
cout<<"The fourth line is:\n" << line << endl;
return 0;
}
You may also want to check that you actually read as many lines as the loop went. So to check to see if you have reached EOF or not, change line 17 to read:
1 2
if (!f.eof()) cout<<"The fourth line is:\n" << line << endl;
else cout<<"There aren't that many lines in the file.\n";
Thank Duoas. Your code is much better than mine. I had looked at the reference files on getline but didn't know how to make it work with ifstream. I was just happy to have a something that could worked for this one program.