Home > front end >  scanf returns non 0 value againt wrong input
scanf returns non 0 value againt wrong input

Time:11-01

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: ");


    }
}

CodePudding user response:

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");
}

CodePudding user response:

You may want to read an entire line using fgets (always check the return value), then use if (sscanf(line, "%d%n", &choice, &size) >= 1 && size == strlen(line)) (see also sscanf).

Alternatively, instead of sscanf you can use strtoul or strtoull.

  •  Tags:  
  • c
  • Related