I have a problem using getline method to get a message that user types, I'm using something like:
string messageVar; cout << "Type your message: "; getline(cin, messageVar);
However, it's not stopping to get the output value, what's wrong with this?
The concept of pointers is used by getline(). For reading text, the getline method is the ideal way. The getline method reads a full line from a stream, such as a newline character. To finish the input, use the getline function to generate a stop character.
When getline is successful, it returns the number of characters read (including the newline, but not including the terminating null). This value enables you to distinguish null characters that are part of the line from the null character inserted as a terminator.
First, getline() is not in the C standard library, but is a POSIX 2008 extension. Normally, it will be available with a POSIX-compatible compiler, as the macros _POSIX_C_SOURCE will be defined with the appropriate values.
Reading strings: get and getlineThe functions get and getline (with the three parameters) will read and store a c-style string. The parameters: First parameter (str) is the char array where the data will be stored.
If you're using getline()
after cin >> something
, you need to flush the newline character out of the buffer in between. You can do it by using cin.ignore()
.
It would be something like this:
string messageVar; cout << "Type your message: "; cin.ignore(); getline(cin, messageVar);
This happens because the >>
operator leaves a newline \n
character in the input buffer. This may become a problem when you do unformatted input, like getline()
, which reads input until a newline character is found. This happening, it will stop reading immediately, because of that \n
that was left hanging there in your previous operation.
If you only have a single newline in the input, just doing
std::cin.ignore();
will work fine. It reads and discards the next character from the input.
But if you have anything else still in the input, besides the newline (for example, you read one word but the user entered two words), then you have to do
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
See e.g. this reference of the ignore
function.
To be even more safe, do the second alternative above in a loop until gcount
returns zero.
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