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);
    }
}
9
  • 1
    while( 1) is an infinite loop. How to exit it? Commented Mar 25, 2021 at 15:14
  • 2
    You read an integer. Then quantity>='0' will always be false ('0' means ASCII character 0) Commented Mar 25, 2021 at 15:15
  • You should add a break statement where you are supposed to exit the loop. Commented Mar 25, 2021 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.. Commented Mar 25, 2021 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 Commented Mar 25, 2021 at 15:26

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.