Search code examples
cclion

How to make user input correctly


The question is about the part of code you can see below. I have two variables leftLimit and rightLimit. Their values should strictly be from -1 to 1 (not included). Ok, I solved this problem. When the input is >= than |1| program will ask until needed value is input. But it only works when input has digital value. When input is a or / and so on, I get the end of program and nothing works. How can I fix it? How to prevent my program from non-digital input?

#include <stdio.h>
#include <math.h>
int main() {
double leftLimit, rightLimit;
printf("Enter the left limit: ");
scanf ("%lf", &leftLimit);
while (fabs(leftLimit)>=1) {                
    printf("\nYou typed a wrong limit, try again: ");
    scanf("%lf", &leftLimit);
}
printf("\nEnter the right limit: ");
scanf("%lf", &rightLimit);


while (fabs(rightLimit)>=1) {                 
    printf("\nYou typed a wrong limit, try again: ");
    scanf("%lf", &rightLimit);
}

Solution

  • scanf() is ill-suited for user input. Prefer fgets() possibly followed by sscanf() or strtol() or strtod()

    double leftLimit;
    char buffer[1000];
    for (;;) {
        printf("Enter left limit: ");
        fflush(stdout);
        if (!fgets(buffer, sizeof buffer, stdin)) exit(EXIT_FAILURE);
        char *err;
        leftLimit = strtod(buffer, &err);
        if (*err != '\n') continue;
        if (fabs(leftLimit) >= 1) continue;
        break; // all ok
    }
    printf("Accepted left limit of %f.\n", leftLimit);