Need help with getline() [duplicate]

The getline(cin, str); reads the newline that comes after the number read previously, and immediately returns with this “line”. To avoid this you can skip whitespace with std::ws before reading the name:

cout << "Enter number:";
cin >> number;
cout << "Enter name:";
ws(cin);
getline(cin, str);
...

Note that this also skips leading whitespace after the newline, so str will not start with spaces, even if the user did input them. But in this case that’s probably a feature, not a bug…

Leave a Comment