I'm self studying C++ and I'm actually back-tracking a bit in order to clarify things. My question revolves around why in the following code is the cin.fail() == true
.
#include <iostream>
using namespace std;
int main()
{
char getdata;
cout << "Enter one character: ";
cin >> getdata;
cin.get();
char line[20];
cout << "\nEnter a line of text 20 characters max: ";
cin.get(line,20);
cout << "\nLine of text entered : " << line;
//cin.get();
char line2[20];
cout << "\nEnter another line of text 20 characters max: ";
cin.get(line2,20);
cout << "\nSecond line of text entered : " << line2;
cout << "\n\nNow at the end of the program";
cout << "\nFirst character of line[20] " << (int)line[0] << endl;
cout << "First character of line2[20] : " << (int)line2[0] << endl;
if (cin.eof())
cout << "\ncin.eof() = true";
else
cout << "\ncin.eof() = false";
if (cin.fail())
cout << "\ncin.fail() = true";
else
cout << "\ncin.fail() = false";
// exit routine
cin.clear();
while (cin.get() != '\n')
continue;
cin.get();
return 0;
}
The crux of the problem, intended for learning purposes, is that after the line cin.get(line,20);
the newline character remains in the input queue. The very next cin.get(line2,20)
, from a users point of view, is ignored or bypassed. The array line2
is in fact assigned the null character as indicated by the cout << "....line2[20]...."
statement.
I'm curious or confused as to why the cin.fail() error has occurred since the array line2
has been assigned the null character.
As I've just written this, it's made me think a little. Is it the case that cin.get(array, size) leaves the newline character in the input queue and since the first character is a newline character, it's ignored and therefore nothing to assign to the array variable, hence an error state created. I'll post this question anyway.