i am having trouble with a loop that reads text from a text file. The problem is that i am not able to read the last line of text.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
ifstream read
read.open(argv[1]); //i am passing parameters a text file to main.
if (read.fail())
{
cout<<"file did not open check it\n";
system("pause");
return -1;
}
char str[101]="" ;
read.getline(str,101);
while (!read.eof())
{
cout<<"output "<<str<<endl;
read.getline(str,101,'\n');
}
So when i output the text i am missing the last line of the text
Any help would be greatly appreciated, thanks.
Its just that i was fixed on having it read a line of text first BEFORE the eof() test, i heard that was the way to go for this kind of task, or something like that.
Can you tell me what would be another test that would do basically the same inside the while loop , but using getline instead?
Its just that i was fixed on having it read a line of text first BEFORE the eof() test
ifstream::getline stops if it sees the end-of-file character regardless, so there's no danger in doing it the way I showed. The only thing is if it's an empty file, it would show output (nothing). I guess you can check to see if str is non-empty before outputting it.
Can you tell me what would be another test that would do basically the same inside the while loop , but using getline instead?
std::getline only takes a std::string. You could copy the char* using std::string.c_str(). You'll have to dynamically allocate your char* if you want to use it after the string goes out of scope.