Reputation: 39
if i input "1k"(or any number followed by letters) into scanf at this configuration i still get a true (non 0) returned from the function, is there any way to explicitly return false if anything but integers are present? basically i wanna know if my string is only numbers or not
p.s. legal switch checks if my input is one of a few given options
void clearBuffer() {
while (getchar() != '\n') {}
}
int getChoice(){
int choice = 0;
//clearBuffer();
while (scanf("%d",&choice)!=0 ||!legalSwitch(choice))
{
clearBuffer();
printf("\nWrong choice, please choose an integer between 1 to 3: ");
}
}
Upvotes: 1
Views: 116
Reputation: 39
adding a getchar()!='\n'
into the while loop condition seemed to solve my issue, however im 90% certain this isnt the way to go but this will have to do for now
Upvotes: 0
Reputation: 223689
The %d
format specifier reads digits until it encounters a non-digit. Whether that non-digit is whitespace or some other character doesn't matter.
What you can do instead is use fgets
to read a full line of text, then use strtol
to parse the value, using the endptr
parameter to see where parsing stopped. If it points to anything other than a newline or a null byte, you know there were extra characters entered.
char line[100];
fgets(line, sizeof line, stdin);
char *p;
long x = strtol(line, &p, 10);
if (*p != '\n' && *p != 0) {
printf("not an integer\n");
} else if (errno != 0) {
printf("value out of range\n");
}
Upvotes: 1