-
getline trouble
This must be something simple, but its driving me mad!! Why does the code shown below not extract the string for the school? All the other bits wrok fine, except the
Code:
cin.getline( school, MAX, '\n' );
bit doesn't seem to execute :(
Code:
const int MAX = 30;
system( "cls" );
char first[ MAX ];
cout << "\nEnter first name : ";
cin.getline( first, MAX, '\n' );
char last[ MAX ];
cout << "\nEnter last name : ";
cin.getline( last, MAX, '\n' );
int age;
cout << "\nEnter age : ";
cin >> age;
if( cin.fail( ) )
{
cerr << "Bad input fool!" << endl;
return false;
}
cin.ignore( 80, '\n' );
char sex;
cout << "\nSex ( M or F ): ";
cin >> sex;
if( sex != 'm' && sex != 'M' && sex != 'f' && sex != 'F' )
{
cerr << "Bad input fool!" << endl;
return false;
}
char school[ MAX ];
cout << "\nEnter name of school : ";
cin.getline( school, MAX, '\n' ); //this bit aint working!
char grade;
cout << "\nEnter competitors grade :";
cin >> grade;
int heightOrWeight;
cout << ( age < 18 ? "\nEnter height ( cm ): " : "\nEnter weight ( kg ) : " );
cin >> heightOrWeight;
-
You forgot one of these
cin.ignore( 80, '\n' );
Which you need before each cin.getline() to tidy up after cin >> var; calls.
-
Should they come after all input then? I've only ever used ignore after reading integer values.
-
Salem's right.
Different data types may be handled by different buffers, but the fact is that you need to flush the rascal to be sure.
In your case, you're inputting char data in back-to-back operations. The '\n' character may very well not be removed from the stream when you input the school name.
getline() reads to, and consumes '\n' (as opposed to get() which reads to, but leaves, '\n').
Fair guess? getline() reads and "eats" the '\n' character still in the stream, and then leaves the pointer at the start of the school name sitting and waiting for somewhere to go.
In other words, the school name is there, but still stuck in the stream buffer. Follow Salem's advice.
-Skipper
-
always use ignore() before calls to get() or getline() unless you are absolutely sure what's already in the istream buffer.