I was using getline() function and it was getting skipped. I searched through the forum and found the tutorial on how to flush the input stream but there is one thing that is still unclear to me :

getline() uses newline character as a delimiter. So when a '\n' is found at the end in input stream getline() is skipped. As stated in the tutorial, formatted stream leaves a newline character in the stream and the mixed/non-formatted one consumes it. So shouldn't
getline be skipped in formatted stream rather than in non-formatted one??

P.S : I would've posted in the same tutorial but i think it was locked, so please bear with me for starting a new thread.

Recommended Answers

All 3 Replies

It's certainly confusing, but straightforward once the concept is understood. Formatted input methods ignore leading whitespace. Unformatted input methods don't ignore leading whitespace. The newline character is whitespace. Finally, getline() terminates when it detects a newline.

So the pattern where getline() is "skipped" would be formatted input followed by getline(), which is unformatted:

cin >> x;
getline(cin, y); // Likely to be "skipped"

Now, I say "skipped" because getline() isn't really being skipped. It's being called and successfully terminating after reading the first character, which is a newline. The reason people say it's being "skipped" is because they don't realize the newline is there or what it represents to getline().

Thank You. I understand now. So to be precise cin (or cin.get) leaves the stream as unformatted and hence the next getline would be "skipped". I also understood that getline() is getting terminated successfully from the tutorial, I mentioned it to be analogous to other's problems.
Just one thing though - Does every input method not having a delimiter leaves input stream as unformatted?

leaves the stream as unformatted

The stream is nothing more than a series of characters. The difference between formatted and unformatted is how you read those characters.

For example, getline() is an unformatted operation; it simply grabs characters up to a newline and doesn't require those characters to be in any special format. operator>>() is a formatted operation; it tries to interpret a value of the specified type and perform a conversion. If the characters aren't formatted as expected for a value of the specified type, the operation fails.

You're overcomplicating things. The root of the problem is that operator>>() stops reading at whitespace and leaves it in the stream. That's not a problem if the next operation is another call to operator>>() because it also ignores leading whitespace. But if the next operation is something that doesn't expect whitespace, there can be a problem.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.