Where did i do wrong?

So im trying to get better in this thing but i dunno what i did wrong, it lets me write in the firts cin part but when it gets to the getline part it dosnt work it just skips it, what did i do wrong?.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int age;
    string name;
    cout << "Hallo " << endl;
    cout << "Wie alt bist du?" << endl;
    cin  >> age;
    cout << "Toll!  Und wie alt bist du? :" << endl;
    getline(cin, name);
    cout << "Schön dich kennen zu lernen " << name << " !" << endl;
    cout << age << " ist ein tolles alter! :) " << endl;





    return 0;
Ok. cin >> age gets the age digits from the keyboard but does NOT get the terminating newline. getline() then sees the newline from before and exists with out obtaining the name. There are various ways around this, but for a simple way try:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

using namespace std;

int main()
{
	int age {};
	string name;

	cout << "Hallo " << endl;
	cout << "Wie alt bist du?" << endl;
	cin >> age;
	cin.ignore();

	cout << "Toll!  Und wie alt bist du? :" << endl;
	getline(cin, name);

	cout << "Schön dich kennen zu lernen " << name << " !" << endl;
	cout << age << " ist ein tolles alter! :) " << endl;
}


Note that this assumes that a valid number was entered for age. If an invalid number (eg contains non-digits) was entered, then the stream enters a 'fail state' and the following getline() will also fail.
Last edited on
When you as user type the number, you do type 'Enter' too, don't you?

The cin >> age; reads only the digits and leaves the newline into the stream.
The following getline(cin, name); then reads that newline.

You have to read/discard the newline that is after the integer (if there is any).
For example:
1
2
getline(cin, name);
if ( name.empty() ) getline(cin, name); // if we get "nothing" on first try, then read more 
Topic archived. No new replies allowed.