While getline() always skips the last line

I am trying to read from a text file using stdin my text file contains something like this:

Hello world
This is a test

Goodbye



Notice there are 4 lines in the text file, and one empty newline.
I use this to read the file:


1
2
3
4
5
6
7
8
9
10
11
int main() {
	string input;
	int count;
	while(getline(cin,input)){
		count++;
		cout << input << endl;
	}

	cout << "There are " << count << " lines"<<endl;
	return 0;
}




The output always returns everything but the last line. If I put an extra newline character then it reads it correctly. Moreover it doesn’t print the cout “There are”. But how could I make it so it reads the line even if there’s no newline character at the end?
Last edited on
After adding
1
2
#include <iostream>
using namespace std;


to the beginning of your code, it works fine for me. What compiler are you using?
@dhayden, I do have that in my code already. I'm using Eclipse with MiniGW GCC
@rjphares, this solution requires using file operations which is not what I'm trying to do. It needs to be done using stdin. I should say that the txt is passed as a parameter in the program when executing it
./program < text.txt
Last edited on
It seems to work for me, whether the last line has a newline or not.
$ hd foo.txt
00000000  48 65 6c 6c 6f 20 77 6f  72 6c 64 0a 54 68 69 73  |Hello world.This|
00000010  20 69 73 20 61 20 74 65  73 74 0a 0a 47 6f 6f 64  | is a test..Good|
00000020  62 79 65 0a                                       |bye.|
00000024
$ hd wobble.txt 
00000000  48 65 6c 6c 6f 20 77 6f  72 6c 64 0a 54 68 69 73  |Hello world.This|
00000010  20 69 73 20 61 20 74 65  73 74 0a 0a 47 6f 6f 64  | is a test..Good|
00000020  62 79 65                                          |bye|
00000023
$ ./a.out < foo.txt
Hello world
This is a test

Goodbye
There are 4 lines
$ ./a.out < wobble.txt 
Hello world
This is a test

Goodbye
There are 4 lines
$ 


> I'm using Eclipse with MiniGW GCC
Are you running this from within the IDE, or from a separate command line?
I tried it with several ways. First I did through the IDE itself which was giving me the problem.
Then within the IDE, I had the input & output redirect to a file. That didn't work either.
Now I just tried manually usually the command line method and surprisingly it works. I'm not sure why it doesn't work with the other methods. But then when it reaches this line:

cout << "There are " << count << " lines"<<endl;

Why is it returning 4201167 ?
Last edited on
> int count;
Well in the code you posted, you don't initialise count to be 0.
doh! Of course silly me! Now it's working thank you!
I would still appreciate it though if someone can explain better how come getline() wouldn't work correctly from the IDE. It also wouldn't exit the while loop either.
Last edited on
Topic archived. No new replies allowed.