Andrew Backes
Andrew Backes

Reputation: 1904

fgets() getting skipped, how to clear user input?

I am using fgets() to get user input, and then I parse it into a double using sscanf(). Here is my example code:

int menuItem = 0;
char input[3];
printf("Enter valid menu item"); //values are 1, 2, 3, 4, 5, and -1
fgets(input, sizeof input, stdin);
sscanf(input, "%d", &menuItem);

The error occurs if the user enters 3 digits (invalid input, and I want to handle it accordingly), it skips my next fgets() by automatically placing the third digit as the next input. For example, if the user inters 123, it will now skip the next fgets and use the value 3 as the input. How can I clear this, or at most, only read 1 digit (but still being able to handle -1).

Upvotes: 1

Views: 2130

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753970

Your input buffer allows 1 digit, 1 newline, and 1 terminal null '\0', which really isn't big enough.

Suppose the user types 100 followed by a newline. The first call to fgets() will read 2 digits (10), then the second call will read the third digit and newline; then the next call will wait for the next input.

Simply increase your buffer size to something more sensible. For a lot of programs that I write, I use a buffer size of 4096. The POSIX standard sets _POSIX2_LINE_MAX to 2048. If you're unhappy with that, simply go with a convenient number like 64 or 128; you won't go too far wrong.

Your technique with fgets() and sscanf() is definitely the better direction to go, but you should check that sscanf() parsed the correct number of values. One of the advantages of fgets() plus sscanf() is that you can make better reports about what was erroneous in the line that the user entered; this is much less easy to do if you use fscanf() or scanf() directly.

Upvotes: 2

paddy
paddy

Reputation: 63471

Why don't you just make your input array larger? Like 50 bytes... If the user enters that many, they are idiots and deserve strange behaviour =)

This is of course inelegant, but putting it in perspective, you are probably not writing industrial-strength code here. You just want to fix a silly bug, and this is the simplest solution.

[edit]

In case you are confused as to why I suggested this. Your input array is only large enough to hold 2 values, plus a null-terminator. So obviously, you want it to be large enough that you can be sure the user entered a single choice and not two choices

Upvotes: 3

Related Questions