a basic question to cin.ignore()

Aug 9, 2012 at 11:31am
Well, right now, i am trying to understand the cin.ignore() option. So I created following function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

int main()
{
    string name; int age;

   cout << "please enter your age:" << endl;
   cin >> age; cin.ignore(1);
   cout << "please enter your name:" << endl;
   getline (cin, name);

   cout << "I am " << age << " years old and my name is " << name << endl;
    }

In this case, the cin.ignore ignores the "enter", so
getline(cin,name)
wont get ignored. Well, if I change
cin.ignore (1)
to
cin.ignore(2)
, i expected the last digit I entered for int age to dissapear. But it was the first letter of my string name.

And even more surprising was, that you then enter the string name before the
cout << "please enter your name:" << endl;
.

Why?
Aug 9, 2012 at 6:33pm
That's not suprising at all! cin.ignnore(n) extracts n characters. with it being 1, it only extracts the enter. With 2, it waits for another character to be pressed, before continuing.
Topic archived. No new replies allowed.