Using getchar() in a while loop

Because you typed ‘a‘ and ‘\n‘… The ‘\n‘ is a result of pressing the [ENTER] key after typing into your terminal/console’s input line. The getchar() function will return each character, one at a time, until the input buffer is clear. So your loop will continue to cycle until getchar() has eaten any remaining characters from … Read more

getchar does not stop when using scanf

The input is only sent to the program after you typed a newline, but scanf(“%s”, command ); leaves the newline in the input buffer, since the %s(1) format stops when the first whitespace character is encountered after some non-whitespace, getchar() then returns that newline immediately and doesn’t need to wait for further input. Your workaround … Read more

int c = getchar()?

Unlike some other languages you may have used, chars in C are integers. char is just another integer type, usually 8 bits and smaller than int, but still an integer type. So, you don’t need ord() and chr() functions that exist in other languages you may have used. In C you can convert between char … Read more

Clarification needed regarding getchar() and newline

Yes, you have to consume newlines after each input: char1 = getchar(); getchar(); // To consume `\n` char2 = getchar(); getchar(); // To consume `\n` This is not compiler-dependent. This is true for all platforms as there’ll be carriage return at the end of each input line (Although the actual line feed may vary across … Read more

How to clear stdin before getting new input?

How to clear stdin before getting new input? .. so I need something with the same functionality. With portable C this is not possible. Instead suggest a different (and more usual C) paradigm: Insure previous input functions consumes all the previous input. fgets() (or *nix getline()) is the typical approach and solves most situations. Or … Read more