Search code examples
cwindowsgetchar

getchar() not acting as it should?


So, I'm getting some strange results using getchar in Visual Studio 2012 Ultimate. This is the most simple example I could come up with to show that it isn't a code error, and is something else in action.

#include <cstdio>

int main(int argc, char* argv[]) {
    char c = getchar();
    putchar(c);
    return 0;
}

However, the result comes out to(visually) acting a bit like 'cin' in the iostream library. getchar returns one character as it should(the first), but as I press keys, it displays the characters on-screen and does not return until I hit enter. I've searched about a bit, and can't really find any other cases of this occurring, does anyone have any clues as to what's going on here?


Solution

  • Standard input is normally line-buffered. That means that the system will read and store characters as you type them in an input buffer until you've entered a full line of text. The getchar() function reads characters from that input buffer.

    For most purposes, it makes more sense to read your input a full line at a time, and then process the line once you've read it.

    There are ways to get immediate input one character at a time, but they're system-specific (and a bit ugly). Question 19.1 in the comp.lang.c FAQ discusses this.