i cannt fill string variable after int variable

when i want to fill a string variable after int variable the code wont let me fill the string
1
2
3
4
5
6
  string name;
int age;
for (int i=0;i<3;i++) {
cout<<"insert name:  "; getline (cin,name);
cout<<"insert age: "; cin>>age;
}

the output:
insert name: aa
insert age: 1
insert name: insert age: 2
insert name: insert age: 3
Press any key to continue ...
Add this after line 5:

1
2
cin.ignore(1000, '\n');
cin.clear();
Thank you , its solved but can i ask what this 2 lines mean ?
The problem was caused by the newline character being consumed by std::getline after using std::cin (i.e. the character inputted when you pressed the ENTER key after using std::cin).

std::cin.ignore(1000, '\n') fixes this issues, as it ignores all characters up to the newline character once the age is entered.

std::cin.clear() clears the error state of the stream in case of bad input (such as a letter entered for age, instead of a number).
Last edited on
Topic archived. No new replies allowed.