Programming and Graphics

(Kiana) #1

64 Introduction to C++ Programming and Graphics


#include <iostream>
using namespace std;

int main()
{
string name;
int age;

cout << "Please enter your name:" << endl;
getline(cin, name);

cout << "Please enter your age:" << endl;
cin >> age;

cout << name << endl;
cout << age << endl;

return 0;
}

The code will run without any surprises, as long as the input is reasonable.
However, if the order of the input is switched to:


cout << "Please enter your age:" << endl;
cin >> age;

cout << "Please enter your name:" << endl;
getline(cin, name);

the program will not work properly. In this case, the secondcinwill apparently
be skipped, and the user’s name will be printed as null. The reason is that the
getline(cin, name)function accepts theEnterkeystroke character following
the age input as legitimate input.


To remedy this problem, we erase this character by inserting immediately
after the firstcinstatement the command:


cin.ignore()

which deletes one character. To delete twenty-six characters, we state:


cin.ignore(26)

To delete seven characters or discard all characters up to and including a new-
line character, whichever comes first, we state:


cin.ignore(7, ’\n’)
Free download pdf