首页 > 解决方案 > 在 C 编程中检查用户的验证

问题描述

这是我的代码片段。我很困惑为什么数字无法运行。如果我们输入字符/字母,它应该。该行是数字打印“请输入数字”,但不打印。我需要你对此的意见。

这是我的代码:

printf("\nenter the amount of food to be purchased  : ");
scanf("%d", &b);
printf("\n");
            
if (b >= 0) {
 for (a=1; a<=b; a++){
   printf("the price of food of- %d \t : ",a);
   scanf("%d", &c);
   printf("\n");
                
   if (isdigit(c)) {
     printf("Please enter in numeric !!\n");
     while ((getchar()) != '\n'); 
     system("PAUSE");
     goto cashier;
   }
   printf("the amount ordered \t : ");
   scanf("%d", &d);
   printf("\n");
                
   if (isdigit(d)) {
     printf("Please enter in numeric !!\n");
     while ((getchar()) != '\n'); 
     system("PAUSE");
     goto cashier;
   }

标签: c

解决方案


scanf("%d", &c);. 将一个整数读入 c。当您调用 时isdigit(c),您不是在检查输入的字符串是否为数字,而是在检查输入的数字是否对应于表示数字的 ascii 字符。这不是预期的行为。你想要的是这样的:

  while (scanf("%d", &c) != 1) // Repeatedly get input until scanf reads 1 integer.
  {
    while (getchar()!='\n'); // Clear stdin.
    puts("Please enter a number!");
  }
// The resulting number is now stored in c.

这将尝试将数字(不是字符串)读入 c。如果用户没有输入 1 个数字,scanf()则不会返回 1,循环将重试。确保 c 被声明为 anint而不是 a char,否则 128 以上的数字将溢出。


推荐阅读