Perhaps this question has been asked or even has a thread written about it so I apologize if it's been asked before however I can't seem to find a solid answer online.

I read the article: Written by Narue about using getline instead of cin when obtaining input from the user.
My question however; Is it a good idea to "generally" stick with getline input, or can I use getchar when only needing a character (such as a 'y' or 'n').
Many articles talk about people having problems but no one really explains it so I can atleast make a somewhat researched decision.

Thanks guys,
Happy New Years :)

Recommended Answers

All 2 Replies

The main difference is getchar returns the next character entered, getline waits for a newline character before returning. Which one to use depends on your needs.

My question however; Is it a good idea to "generally" stick with getline input, or can I use getchar when only needing a character (such as a 'y' or 'n').

When you type the 'y' or 'n' you also type the Enter key. You have to call getchar() twice if you want to empty the keyboard. But what if I actually type "yes" or "no" instead of just 'y' or 'n'? getline() will empty the keyboard buffer regardless of how may keys you type (assuming you use std::string or char array that is larger than the number of characters in the keyboard buffer).

Programmers have lots of problems with getchar() because they fail to empty the keyboard buffer of the '\n' character before asking for more keyboard input using getline(). getline() will see the '\n' in the keyboard buffer and stop.

So, IMO use getline() with std::string simply because it's easier and safer to use.

Be a part of the DaniWeb community

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