Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help with getline() [duplicate]

Tags:

Is there a reason why if in my program I am asking the user for input, and I do:

int number; string str; int accountNumber;  cout << "Enter number:"; cin >> number; cout << "Enter name:"; getline(cin, str); cout << "Enter account number:"; cin >> accountNumber; 

Why after inputting the first number, it outputs "Enter Name", followed immediately by "Enter Account Number" before I even get to input my "str" for the getline(cin, str) line? Thanks!

like image 884
Jon Avatar asked Nov 16 '09 20:11

Jon


People also ask

Does Getline work with double?

cplusplus.com/reference/istream/istream/getline getline doesn't take a double argument, as it's telling you. it's there to get lines of data (aka char arrays / strings) not numbers.

What is the problem with Getline in C++?

The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage.

Can we use Getline for multiple times in a C++ program?

You can just use the static method tinyConsole::getLine() in replace of your getline and stream calls, and you can use it as many times as you'd like.


1 Answers

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...

like image 157
sth Avatar answered Sep 21 '22 19:09

sth