0

I'm having a problem with a while loop. I have to enter a number which is bigger than 0 and below 81. when I use numbers like -1,0,1,2,82 it is going good and I get the expected result, but when I use a letter it keeps going through my while loop. I've used the debugger in eclipse and when I'm at the while loop amount is automatically set to '0' because of the failed scanf. Why does it keep looping when I insert a letter?

eclipseDebug

#include <stdio.h>
#include <stdlib.h>

int main(){
    int amount = 0;
    printf("Give a number:\n");
    fflush(stdout);
    scanf("%d",&amount);
    while(amount <= 0 || amount >= 81){
        printf("Wrong input try again.\n");
        printf("Give a number:\n");
        fflush(stdout);
        scanf("%d",&amount);
    }
    return EXIT_SUCCESS;
}
6
  • %d is not for letter. You need to convert your char inputs to int before validation in while.
    – Dayal rai
    Apr 25, 2014 at 11:34
  • Using wrong format specifiers is undefined behavior.
    – 0xF1
    Apr 25, 2014 at 11:35
  • @Dayalrai I get that, but at the moment it sets amount to 0. which is an integer. so it should be valid for my while. right? Apr 25, 2014 at 11:40
  • 2
    If the input is a letter, and amount is set to zero, then of course the loop continues, because the while clause evaluates to true: while (amount <= 0 || <-- amount is less then, or equal to zero. A quick tip: research the problems that scanf has, and check the return values of functions as much as possible Apr 25, 2014 at 11:44
  • 2
    You must check the return value of scanf() before you use the scanned value. It's I/O, it can fail. Not sure why so many fail at this.
    – unwind
    Apr 25, 2014 at 11:45

2 Answers 2

4

You need to make sure the scanf() worked. Use the returned value to do that

if (scanf("%d", &amount) != 1) /* error */;

When it doesn't work (because eg a letter was found in input) you probably want to get rid of the cause of the error.

A better option to get input from users is to use fgets()

1

See this related question: scanf() is not waiting for user input

The reason is that when you press enter with a char, scanf failed and didn't eat up the char in the input feed. As a result, the next block begins having whatever you entered before.

You can check that by adding a getchar() before the scanf() inside the while loop. You'll notice that it'll repeat the while loop as many times as your line has invalid characters, then stop and wait for input. The getchar() ate one of the invalid chars in the input each time the loop ran.

It would be better not to use scanf like that, though. Take a look a this resource: Reading a line using scanf() not good?

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.