Input validation

Please tell me how to validate the input as numerical only. I need to use a loop to validate the input.

Thanks in advance!


  • What do you mean by " you need to use a loop"? If the validation is for a single digit ( 0 to 9) input then the isdigit() will work for you. If the validation is for a two or higher digit number then the approach is quite different. Could you confirm what exactly you need.

    But then I am just a toddler in C / C++.
  • I am a toddler too and this is my task in the course-to use a loop. Like while(condition) -true-false.
  • [color=Blue]Numerical definition may be quite complex:


    If you need to validate all of these cases - you need some work to do. However, for simple integer validation you need two things:

    1. Check for +- sign at the first character and if sign is found then skip that character.
    2. Check every next character as being a digit and if so, then you got a correct integer value.
    3. If you meet character with value == 0, then stop checking
  • C Primer Plus book gives an option to check if the input is an integer or not through the return value of scanf. If the return value is != 1 than the input is not an integer. But I can't make the while loop that works. Any ideas for how the code should look like?
  • [color=Blue]If you want to use the scanf return value then loop to enter few values will looke like this:[/color]
    int flag=1, value;

    while (flag == 1)
    printf ("
    ENTER VALUE: ");

    [color=Green]// scan value into integer[/color]
    flag = scanf ("%d", &value);

    [color=Green]// use value if it is an integer[/color]
    if (flag == 1)
    [color=Green]// use it here ...[/color]
  • Thanks for the idea. I saw other examples with the same structure working just fine. But for my program I need the user to re-enter the value if it's incorrect. So I need to use !=1. Unfortunately, that doesn't work. The loop stops at printf"Please re-enter" and never ends.
  • [color=Blue]Please, post your code.[/color]
  • int main(void)
    //declare variables
    int number, status;
    int i = 1;

    //ask the user for the desired number and validate the input. Only numeric input allowed.
    printf("Please enter a number:");
    status = scanf("%d", &number);
    while(status != 1)
    printf("The input is not numeric. Please try again:");
    status = scanf("%d", &number);

    //print the amount of asterisks
    for(i=1; i<= number; i++)

    }while(number >= 1);

    //end of the program

    What is really interesting for me is not how to fix the code(I already got an answer)but why the loop is not working. Thanks.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!