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 != '
');
}
question from:
https://stackoverflow.com/questions/65890433/scanf-issue-input-of-integer-followed-by-character-ex-1p-for-a-single-input 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…