[C] getchar() returns too quickly

May 15, 2010 at 8:28pm
Hi, I am trying to get user input through getchar(). However, it seems that the second time I call it, it returns immediately.

1
2
3
4
5
6
7
8
#include <stdio.h>

int main()
{
    getchar();
    getchar();
    return 0;
}


This would only take input one time. Is there any way to avoid this undesired behavior? Thanks
May 15, 2010 at 10:03pm
This would only take input one time.

Nope, it takes input two times :P The first is the character you type and the second is the newline character generated by the pressing of enter. Check it out like this: if you don't enter a character it takes two enter key-presses to quit the program.
May 15, 2010 at 10:08pm
Check if the result for the first getchar() was a '\n'. Only call getchar() a second time if it wasn't.
May 15, 2010 at 11:43pm
you can use #include <iostream.h> and use (cin>>var;) to read from the keyboard the inf.
before the return use cin.get(); whit this yoou have press one key to exit of your program.
May 16, 2010 at 2:18am
Keep the console open long enough to see your program's output
http://www.cplusplus.com/forum/articles/7312/

All user input ends in ENTER
http://www.cplusplus.com/forum/beginner/22128/#msg116074
Topic archived. No new replies allowed.