Reputation: 1281
So, I've found the specific line of a file that I want to read, but what I've got isn't working:
string str;
int target = 0;
ifstream record;
record.open("Record.txt");
target = std::count(std::istreambuf_iterator<char>(record), std::istreambuf_iterator<char>(), '\n') - 8;
cout << target << endl;
for(int lineNum = 0; lineNum <= target; lineNum++)
{
getline(record, str);
if(lineNum == target)
{
cout <<"the id: "<< str << endl;
}
}
In the above, I use std::count to count the lines of a file. I know that I'll always want to read the eigth line from the bottom, so I set my target to that. Next, I loop through each line up to target times, and do a check to see if i'm at the target line. If so, then cout the line.
However, it's not giving me anything. For a file with 22 lines, I get the following output:
14
the id:
Can someone point out what I'm doing wrong or give me some hints? Thanks!
Upvotes: 0
Views: 179
Reputation: 122001
The record
stream will be eof()
after the std::count()
call but the code never checks the return value of std::getline()
so is unaware that it is failing: always check return value of read operations. This means that str
is never populated hence nothing is printed after the "thid id: "
message.
You need to reset the stream or re-open it.
Upvotes: 3