while (!cin.eof) help

Sep 20, 2011 at 3:55am
Hi everyone

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.
Sep 20, 2011 at 4:05am
You are reading the last line. You're just not outputting it.

1
2
3
4
5
6
7
char str[101]="" ;
read.getline(str,101);
while (!read.eof())
{
    read.getline(str,101,'\n');
    cout<<"output "<<str<<endl;				
}
Sep 20, 2011 at 4:15am
Thanks a lot, that took care of the problem.

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?
Sep 20, 2011 at 4:25am
1
2
3
std::string str;
while(getline(cin, str))
  cout<<"output "<<str<<endl;
Sep 20, 2011 at 4:28am
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?

You mean like this?

1
2
3
4
5
6
7
8
9
10
11
#include <string>
using namespace std;
//...

string str;

while(!read.eof())
{
    getline(read, str);
    cout<<"output "<<str<<endl;
}
Last edited on Sep 20, 2011 at 4:33am
Sep 20, 2011 at 4:31am
I really need to use a char array for this? Is there another way?

if not its all good, i think i will be allright
Sep 20, 2011 at 4:40am
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.
Sep 20, 2011 at 4:41am
ok thanks for all your help
Sep 20, 2011 at 4:42am
(and by dynamically allocate I actually meant do a deep copy of it which doesn't necessarily need dynamic allocation)
Last edited on Sep 20, 2011 at 4:44am
Sep 20, 2011 at 4:42am
you can use the global getline version in the <string> header if you don't want to use the char array.
http://www.cplusplus.com/reference/string/getline/
Topic archived. No new replies allowed.