0

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

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

5 Comments

it doesn't work, it endlessly want me to input left limit, even if input is correct. And what does fflush(stdout) do?
My bad ... *err must be the ENTER, not '\0', code corrected
fflush(stdout); forces the prompt above on the screen. Usually stdout is line-buffered and "Enter left limit: " does not have a newline so it might be stuck inside stdout buffers
but I also have a few questions about you line if (!fgets(buffer, sizeof buffer, stdin)) exit(EXIT_FAILURE); . I can understand more or less this part: (!fgets(buffer, sizeof buffer, stdin)) but I don't understand exit(EXIT_FAILURE) at all. I'm just at early stage of learning C, so I would be grateful if you explained it, or at least gave me link, where i can learn about it. Sorry for the insolence, thank you.
It's just error management --- in the very unlikely event of an input error (network failure, milk spilt on keyboard, cat chew cable, ...), in which case fgets() returns NULL, exit the program rather than keep trying for ever. Some (most??) people, confidently (!!!), just skip the error validation here :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.