开发者

Validate Input to a C Program

开发者 https://www.devze.com 2023-01-11 05:32 出处:网络
i have a c program in which i am accepting 2 numbers as input. How do i validate if input entered is numbers only and not characters.

i have a c program in which i am accepting 2 numbers as input. How do i validate if input entered is numbers only and not characters.

v开发者_StackOverflowoid main()
{
  int a,b;
  printf("Enter two numbers :");
  scanf("%d%d",&a,&b);
  printf("Number 1 is : %d \n Number 2 is : %d",a,b);
}

[Edit] Added Sample Code


Besides the other interesting suggestions (especially the one with scanf), you might also want to use the isdigit function:

The isdigit() function shall test whether c is a character of class digit in the program's current locale

note that this function examines only ONE char, not an entire bunch of them.

It is always good practice to resort to already-built functions; there are intricacies you might not be aware of even in the simplest task, and this will make you a good programmer overall.

Of course, in due time you might want to look at how that function works to get a good grasp of the underlying logic.


scanf returns the number of items that it has successfully scanned. If you asked for two integers with %d%d, and scanf returns 2, then it successfully scanned both numbers. Any number less than two indicates that scanf was unable to scan two numbers.

int main()
{
    int a,b;
    int result;

    printf("Enter two numbers :");
    result = scanf("%d%d",&a,&b);

    if (result == 2)
    {
        printf("Number 1 is : %d \n Number 2 is : %d",a,b);
    }
    else if (result == 1)
    {
        // scanf only managed to scan something into "a", but not "b"
        printf("Number 1 is : %d \n Number 2 is invalid.\n", a);
    }
    else if (result == 0)
    {
        // scanf could not scan any number at all, both "a" and "b" are invalid.
        printf("scanf was not able to scan the input for numbers.");
    }
}

One other value that scanf may return is EOF. It may return this if there is an error reading from the stream.

Also note that main returns int, but you have it declared with void return.


Read user line of text input as a string. This greatly simplifies error handling.

int a = 0, b = 0;
char buf[100];

for (;;) {
  printf("Enter two integers :");
  if (fgets(buf, sizeof buf, stdin) == NULL) {
    printf("Input closed\n");
    break;
  }

Then test the string for 2 ints with no following junk. Use sscanf() (simple) , strtol() (more robust), etc.

  int n;        // %n records where scanning stopped
  if (sscanf(buf, "%d%d %n", &a, &b, &n) == 2 && buf[n] == '\0') {
    printf("Number 1 is : %d \n Number 2 is : %d", a, b);
    break;
  }
  printf("<%s> is not 2 integers.  Try again\n", buf);
}

More advanced code uses strtol() to validate and also detect excessively long lines of input.

0

精彩评论

暂无评论...
验证码 换一张
取 消