0

I keep getting values ​​as long as the user does not enter a positive integer (and I control if user entered negative values or if user entered an integer). I try to do it without using isdigit, it enters an infinite loop when I enter a character.

int quantity;
        
printf("Please enter term(s) number");
scanf("%d",&quantity);
while( 1){
    if(quantity<0){
        printf("Please enter “positive”  number");
        scanf("%d",&quantity);
    }

    if(!(quantity>='0' && quantity<='9')){
        printf("Please enter “a”  number");
        scanf("%d",&quantity);
    }
}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    `while( 1)` is an infinite loop. How to exit it? – Paul Ogilvie Mar 25 '21 at 15:14
  • 2
    You read an integer. Then `quantity>='0'` will always be false (`'0'` means ASCII character 0) – Paul Ogilvie Mar 25 '21 at 15:15
  • You should add a `break` statement where you are supposed to exit the loop. – Roberto Caboni Mar 25 '21 at 15:15
  • 1
    The 'character' is presumably non-numeric. This blocks the input until you remove it. One easier way to deal with this to use `fgets()` for all input and then `sscanf()` and then, if `sscanf()` returns the wrong value, or the entry is the wrong value, you dump the string and ask for another.. – Weather Vane Mar 25 '21 at 15:20
  • @PaulOgilvie while( ( !(quantity>='0' && quantity<='9')) || quantity<0) when i use this and enter a character there is still infinite loop,ı dont know how to solve it – user15465584 Mar 25 '21 at 15:26
  • @RobertoCaboni If user provides a positive integer (not a character or a negative integer) I want to exit and I typed this way which part should I edit – user15465584 Mar 25 '21 at 15:30
  • @WeatherVane honestly i don't use anything but scanf because homework – user15465584 Mar 25 '21 at 15:31
  • Please see [How to clear input buffer in C?](https://stackoverflow.com/questions/7898215/how-to-clear-input-buffer-in-c) Particularly [this answer](https://stackoverflow.com/a/26081123/4142924). That means you will use `getchar()` but you can find a way to do it with `scanf()` too. – Weather Vane Mar 25 '21 at 15:36
  • @WeatherVane Thank you very much, that was the problem, solved.if you can type this an answer i can approve it,i dont know another way to close the session*/ – user15465584 Mar 25 '21 at 15:51

1 Answers1

1

Use fgets() to get an entire line. You use strtol() to parse the line as an integer, checking if it consumed the entire line.

char *end;
char buf[LINE_MAX];

do {
     if (!fgets(buf, sizeof buf, stdin))
        break;

     // remove \n
     buf[strlen(buf) - 1] = 0;

     int n = strtol(buf, &end, 10);
} while (end != buf + strlen(buf));

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
samaritan
  • 74
  • 9