C++: getline function

Getline (cin, var) function is used to input from the keyboard. It helps to get entire line until Enter or Return keys are pressed. For instance, if we want to get full names of people from the keyboard we should use this function.

However, when I write the following code, it got semantic error:

#include <iostream>
#include <string>
using namespace std;
// struct type person
struct person {
string name;
int age;
string address;
};
int main() {
person ps;
string address;
cout << “The name: “; getline(cin, ps.name);
cout << “The age: “; cin>> ps.age;
cout << “The address: “; getline(cin, ps.address);
cout << “The name is: ” << ps.name << endl;
cout << “The age is: ” << ps.age << endl;
cout << “The address is: ” << ps.address << endl;
}

The performance of the code illustrated as following:

1

I do not the reason why I can’t input addresses.

After asking some people, I got the answer:

Indeed, its >>’s fault. The thing is that cin>> reads one word and stops immediately, thus leaving the ‘\n’ from pressing Enter in the stream. This ‘\n’ is then found by getline. It would be good to have a cin.ignore() after every cin>> so that there is never any rubbish in the stream.

Then I corrected the above code and it totally worked properly.

int main() {
person ps;
string address;
cout << “The name: “; getline(cin, ps.name);
cout << “The age: “; cin >> ps.age; cin.ignore();
cout << “The address: “; getline(cin, address);
cout << “The name is: ” << ps.name << endl;
cout << “The age is: ” << ps.age << endl;
cout << “The address is: ” << address << endl;
}

Advertisements

#cin, #error, #error-prone, #getline, #string