problem with get and getline

int main()
{
char a[3];
char b,c,d;

cin.getline( a,3 );
cin.get(b);
cin.get(c);
cin.get(d);
cout << a << endl << b << endl << c << endl << d << endl;
}

When I tried to run the above code and typed in a list of letters "fldaslk", I got the following result on the output screen.

fl
V

"


Can someone explain the output shown? I have problem using get and getline together. Thank you:)
You asked istream::getline() to read a line, that is, a sequence of characters that ends with a newline character.

It failed to do so, because it ran out of the buffer space provided (2 characters, which is how big is a null-terminated byte string that can be stored in an array of 3).

When an input function fails, it sets the failbit on the input stream, so cin.getline(a,3); enabled the failbit on std::cin

When the failbit on a stream is set, no further input from that stream is possible until the error is cleared (e.g. with cin.clear();), so none of your three cin.get()'s did anything. The values you see in b, c, and d, are values of uninitialized variables.
Last edited on
Thank you very much, Cubbi!!!
Topic archived. No new replies allowed.