Samo FiveOTwo
Samo FiveOTwo

Reputation: 53

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?

Upvotes: 1

Views: 143

Answers (2)

Keith Thompson
Keith Thompson

Reputation: 263277

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.

Upvotes: 1

Bryan Olivier
Bryan Olivier

Reputation: 5307

The input is line-buffered, so getchar will only take a character once at least a line of input is typed. If you don't end the line but instead close the input ^D on Linux, I guess ^Z on Windows, then you will see that it will also print the first character.

Upvotes: 1

Related Questions