0

I want to check the user input if it is a number and I want the program to accept only a number as an input. I don't know if I explained myself clearly, I'll try by showing you an example:

int x;
printf("Write a number: ");
scanf("%d", &x);
while(!isdigit(x))
{
    printf("Not valid\n");
    fflush(stdin);
    scanf("%d", &x);
}

I tried using scanf("%d", &x) != 1 as a while condition but it remains inside the loop. Is there a way to ask an input until the user writes a number? For now I just return the function but I'd like not to.

Swordfish
  • 12,971
  • 3
  • 21
  • 43
Goner
  • 31
  • 1
  • 4

1 Answers1

0

You have to check the return value of scanf():

#include <stdio.h>

int main(void)
{
    int x;
    while (printf("Write a number: "),
           scanf("%d", &x) != 1)  // when the number of successful conversion wasn't 1
    {
        fputs("Not valid!\n", stderr);
        int ch;
        while ((ch = getchar()) != EOF && ch != '\n');  // clear stdin from garbage
    }                                                   // that might be left.
}
Swordfish
  • 12,971
  • 3
  • 21
  • 43