Question

The user has to enter a number greater than 0 in order to print some stuff.

my code for when the user enters a number less than 0 uses a while loop. It then asks the user to type in a number again.

while(x<=0){
  print("Must enter a number greater than 0");
  printf("Enter a number: ");
  scanf("%i",&x);}

How can I create an error message formatted similarly to the one above, but for a user who enters a "x" or a word. Thanks

Was it helpful?

Solution

Since the reading is done using scanf with a numeric format, it means that if you enter something that can't be read as an integer (123) or part of an integer (123x is ok, the parsing stops soon after the 3), the scanf fails (i.e. it can't parse the input as number). Scanf returns the number of successfully parsed items. So you expect 1 in your case. You can check the return value (if it's 0, scanf wasn't able to get any number from the input) but as said before you still accept thigs like 123x (and the "residual" x will be parsed in the next scanf from stdin, if you do it).

OTHER TIPS

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

int main(void){
    int x;
    int ok=0;

    do{
        char buff[32], *endp;
        long long num;

        ok = !ok;//start true(OK)
        printf("Enter a number: ");
        fgets(buff, sizeof(buff), stdin);
        x=(int)(num=strtoll(buff, &endp, 0));//0: number literal of C. 10 : decimal number.
        if(*endp != '\n'){
            if(*endp == '\0'){
                printf("Too large!\n");
                fflush(stdin);
            } else {
                printf("Character that can't be interpreted as a number has been entered.\n");
                printf("%s", buff);
                printf("%*s^\n", (int)(endp - buff), "");
            }
            ok = !ok;
        } else if(num > INT_MAX){
            printf("Too large!\n");
            ok = !ok;
        } else if(x<=0){
            printf("Must enter a number greater than 0.\n\n");
            ok = !ok;
        }
    }while(!ok);

    printf("your input number is %d.\n", x);
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top