Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using getline() in C++

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?

like image 829
MGE Avatar asked Sep 13 '13 12:09

MGE


People also ask

How do I use Getline in C?

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.

What is Getline return in C?

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.

Is Getline in C standard?

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.

Does Getline work with C strings?

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.


2 Answers

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.

like image 113
Natan Streppel Avatar answered Sep 20 '22 20:09

Natan Streppel


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.

like image 37
Some programmer dude Avatar answered Sep 22 '22 20:09

Some programmer dude