NB: to avoid misunderstanding, the code is aimed to handle input errors .. i'm asking for integers (no characters) but the user might enter characters by mistake, so how to avoid the following:
I know that scanf sucks but I have to use it for some reasons. So, the problem I'm facing right now is that if I'm scanning a single integer from the user as follow:
scanf("%d",&c);
if the user enters a digit followed by a character, such as: 1k, it's treated as double input not a single one, and checking the return value for the scanf and using flushinput concept doesn't work here. To make my question clearer:
The user is prompted to enter a choice, and in case of invalid choice he'd be asked again (through a loop), so, if he enters for ex:
k, gives the message (it's an invalid input) once, and rescans
k2, gives the message (it's an invalid input) once, and rescans
2k, gives the message (it's an invalid input) TWICE then rescans.
Any hints to solve that issue? Thanks in advance !!
NB: I check the returned value of scanf as follow:
if (scanf("%d",&confirm)!=1)
{
flushInput(); confirm=0;
}
where:
void flushInput()///prevents infinite loops resulted due to character input instead of integer
{
int c; //c ->absorbs the infinite characters resulted due to the entry of chars, using getchar()
while((c = getchar()) != EOF && c != '\n');
}
%d
is for reading numbers(ints) why are you givingchar
type input – IrAMscanf
is almost useless, and it is in fact completely useless for robust error checking, and it is also completely useless for user input in any kind of commercial or production code. – Steve Summitscanf
, or it will take you five times as long (and deliver at most 90% of the error checking) as if you used proper, non-scanf
methods. Sorry to say this, because it's not answering the question, and I know you said you need to usescanf
, but it's really not a reasonable requirement. If you told me I had to do robust input and I had to usescanf
, I would either (a) resign or (b) read whole lines using%[^\n]
, then parse them sanely (that is, just as I would do if I were allowed to callfgets
). – Steve Summitscanf
, it is a pointless exercise from which you will learn nothing useful, except perhaps forbearance. Yes, in the real world, it's important for programs to do robust, error-checked input, but in the real world, nobody implements this usingscanf
. – Steve Summit