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?
@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
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:
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.