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!
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.
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With