Xisso2
Xisso2

Reputation: 1

Illegal to use fflush() in stdin? What to do instead?

char c;
char s[32];
puts("Type a char");
c=getchar();
fflush(stdin);
puts("Type a string");
fgets(s,32,stdin);

Without the fflush(), if you type a character, say "a", and the hit enter, the input buffer contains "a\n", the getchar() peeks the "a", but the "\n" remains in the buffer, so the next fgets() will find it and return an empty string without even waiting for user input.

What should be done instead? As far as i know, it's not defined or standard to use fflush() on an input stream?

Upvotes: 0

Views: 645

Answers (3)

Read about fflush(3); you probably want to call fflush(NULL);before c=getchar(); but that might not work as you want.

Remember that on Linux at least the terminal is often kernel buffered (and also stdio buffered). Read more about tty-s. So you often won't get any input till the user pressed the enter key.

You should rethink your program and read entire lines (often with getline(3) or fgets(3) on a large enough buffer).

If you want to get individual key presses on Linux (or other POSIX systems) you need a library like ncurses (which works with the terminal in raw mode). You might be interested in readline(3)

Upvotes: 0

M.M
M.M

Reputation: 141648

If you are trying to discard the rest of the input line, then do this:

int ch;
while ( (ch = getchar()) != '\n' && ch != EOF) { }

This reads characters until there are no more, or it hits the end of the line.

Note that you should be using int c; rather than char c; . The getchar() function actually does not return a char value; it returns the result of converting that char to unsigned char.

Upvotes: 1

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215517

Don't use getchar when your intent is to read a line of input and interpret one character from it. In this case, read a line with fgets or similar and just inspect the first line.

Alternatively, you can stick with getchar, but then you need to keep reading characters until the end of the line and throw them away before moving on.

Your program could be transformed to (first approach):

char c;
char s[32];
puts("Type a char");
fgets(s,32,stdin);
c=s[0];
puts("Type a string");
fgets(s,32,stdin);

Note that this is missing checking of return values and doesn't handle input longer than 32 bytes, but it's a start and those are separate issues you can work on.

Upvotes: 2

Related Questions