getline() & fstream behavior

I'm testing fin functions and I came across this.

Does anyone have any idea why getline fails to extract the char[]? (i.e.'This is a sentence!') I suspect the extraction operator causes something to happen to the fin buffer.

Expected Output
48
L
This is a sentence!

Actual Output
48
L


[code]
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
ifstream fin("testfile");

char letter;
char stringTwo[256];
int num;

fin >> num>> letter;
fin.getline(stringTwo, 256);
fin >> stringTwo;

cout <<num<<endl;
cout <<letter<<endl;
cout <<stringTwo<< endl;

return 0;
}
[code/]

**********testfile***********

48
L
This is a sentence!
>> leaves newline characters in the stream so you are reading an empty string.
You can tell the stream to ignore the \n before calling getline http://www.cplusplus.com/reference/iostream/istream/ignore/
I used fin.ignore(255, '\n') before the getline call. I got the same output.

I also changed the testfile to

48 L This is a sentence!

and used the ' ' delimiter instead '\n'. Same result.
If you are delimiting the string with ' ', you should remove the fin.ignore part
I removed an extra fin >> stringTwo statement and kept the ignore call. It's working now. Thanks for clearing this up for me.
- Ray

Last edited on
Topic archived. No new replies allowed.