If you provide std::cin.getline() with a third argument?a “stop” character, it ends its input by eating the character and terminating the string. For example:
std::cin.getline(str, 100, '|')
Without this this argument, std::cin.getline() stops when it reaches a new line. For example:
float fl;std::cin >> fl;char str[101]std::cin.getline(str, 101);cin.ignore();
And you type:
3.14
3.14 is read into fl. The new line following the 3.14 still sits on the input buffer.
std::cin.getline(str, 101) immediately processes the new line still on the input buffer. str becomes an empty string.
The illusion here is that the application “skipped” the std::cin.getline() statement.
The solution is to add std::cin.ignore(); immediately after the first std::cin statement. This grabs a character off of the input buffer (in this case, newline) and discards it.
You can call std::cin.ignore() three different ways:
- No arguments: Take a single character from the input buffer and discard it:
std::cin.ignore(); //discard 1 character
- One argument: Take a specified number of characters from the input buffer and discard them:
std::cin.ignore(33); //discard 33 characters
- Two arguments: Discard the number of characters specified or discard characters up to and including the specified delimiter (whichever comes first):
std::cin.ignore(26, ' '); //ignore 26 characters or to a newline, whichever comes first