I have a program that has this code :
#include<stdio.h>
main(){
int input;
char g;
do{
printf("Choose a numeric value");
printf(">");
scanf("\n%c",&input);
g=input-'0';
}while((g>=-16 && g<=-1)||(g>=10 && g<=42)||(g>=43 && g<=79));
}
It basically uses ASCII manipulation to allow the program to accept numbers only .. ‘0’ is given the value 48 by default…the ASCII value – 48 gives a ranges of numbers above (in the while statement)
Anyway, whenever a user inputs numbers AND alphabets, such as :
abr39293afakvmienb23
The program ignores : a,b,r .. But takes ‘3’ as the first input.
For a b and r, the code under the do loop repeats. So for the above example, I get :
Choose a numeric value
>Choose a numeric value>
Choose a numeric value
>3
Is there a way I can stop this ??? I tried using \n%c to scan the character and account for whitespace, but that didnt work 🙁
Please help
thank you very much !
What I understand from your question is that when user enters
abr3, the output you get isNow you do not what these “excessive”
Choose a numeric valueto appear. If user has input abr3, its just take 3 from it and exit. Something like this.Now to do that you have to change format specifier in your
scanf()statement. Try your program withIt tells the scanf to accept all the contents within braces i.e. 0-9. Any other character outside this range is ignored. If user inputs
abr3, a is not in the range, therefore input will remain equal to zero. Moreover,Choose a numeric valuefor a,b and r will not appear.If user input is a number in the range of 0-9, it will be accepted and put into input.
You will have to add a check for input==0.
Hope it helps.