Problem with "getline"

Hey, or better good night!

I have a problem in a very tiny programm, which should just ask questions and list later the answers. But I have a problem when I'm using the "getline();" function twice.

// MAIN_CPP //

#include <iostream>
#include <conio.h>
#include <string>

using namespace std;

int main(){

	//Variables//
	string sName;                    //char arrays better btw.?
        string sSchule;

	int	   iAlter;


	//Questions//
	cout << "		Fragebogen: " << endl << endl
             << "1. Wie lautet ihr Name? ";
	getline( cin, sName );                                  //First getline, because full name needed
	system( "cls" );
	
	cout << "2. Wie alt sind sie?" << endl;
	cin  >> iAlter;
	system( "cls" );
	
	cout << "3. Besuchten sie eine Grundschule? Wenn ja, welche?  ";
	getline( cin, sSchule );	                                          //Second getline, question 
                                                                                   just gets skipped :(
	    cout << "			Informationen: " << endl	
		 << "Name: "   << sName		 << endl
		 << "Alter: "  << iAlter	 << endl
		 << "Schule: " << sSchule	 << endl;                            
 
//with just "cin" their                         
will be of course only the first letters shown, but then the question wont get skipped.

getch();
return 0;
}
1
2
3
cin  >> iAlter;
[...]
getline( cin, sSchule );

You didn't consume the endline character left on the input stream after processing iAlter. getline() stops reading at the first endline character it encounters.

You need to read off and discard that endline, add
cin.ignore();right after cin >> iAlter;
or, to be robust, add
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // (google that)
Topic archived. No new replies allowed.