0

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 :)

3
Contributors
2
Replies
6
Views
4 Years
Discussion Span
Last Post by Ancient Dragon
0

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.

0

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.

Edited by Ancient Dragon

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.