c - 使用 strtol 验证 ANSI C 中的整数输入

标签 c string ansi strtol

我是编程和 C 语言的新手,目前正在大学学习。这是一个作业,所以我想避免直接回答,但更多的是在提示或提示/插入正确的方向之后。

我正在尝试使用 strtol 来验证我的键盘输入,更具体地说,测试输入是否为数字。我查看了这里和其他网站上的其他问题,并遵循了其他用户的说明,但对我没有帮助。

根据我对 strtol 的阅读/理解(long int strtol (const char* str, char** endptr, int base);)如果 endptr 是不是空指针,函数会将 endptr 的值设置为数字后的第一个字符。

因此,如果我要输入 84948ldfk,endptr 将指向“l”,告诉我输入中有数字以外的字符,这会使它无效。

但是在我的情况下,无论我输入什么,我的程序都会返回无效输入。这是我的代码:

void run_perf_square(int *option_stats)
{
   char input[MAX_NUM_INPUT + EXTRA_SPACES]; /*MAX_NUM_INPUT + EXTRA_SPACES are defined
                                              *in header file. MAX_NUM_INPUT = 7 
                                              *and EXTRA_SPACES 
                                              *(for '\n' and '\0') = 2. */
   char *ptr;
   unsigned num=0; /*num is unsigned as it was specified in the start up code for the 
                    *assignment. I am not allow to change it*/

   printf("Perfect Square\n");
   printf("--------------\n");
   printf("Enter a positive integer (1 - 1000000):\n");
   if(fgets(input, sizeof input, stdin) != NULL)
   {
      num=strtol(input, &ptr, 10);
      if( num > 1000001)
      {
         printf("Invalid Input! PLease enter a positive integer between 1 
                  and 1000000\n");
         read_rest_of_line();        /*clears buffer to avoid overflows*/
         run_perf_square(option_stats);
      }
      else if (num <= 0)
      {
         printf("Invalid Input! PLease enter a positive integer between 1 
                  and 1000000\n");
         run_perf_square(option_stats);
      }
      else if(ptr != NULL)
      {
         printf("Invalid Input! PLease enter a positive integer between 1 
                  and 1000000\n");
         run_perf_square(option_stats);
      }
      else
      {
         perfect_squares(option_stats, num);
      }
   }
}

任何人都可以在正确的方向上帮助我吗?显然错误与我的 if(ptr != NULL) 条件有关,但据我了解它似乎是正确的。正如我所说,我已经看过以前类似的问题并接受了答案中的建议,但它似乎对我不起作用。因此,我认为最好寻求适合我自己情况的帮助。

提前致谢!

最佳答案

您正在检查 strtol 的结果顺序错误,检查ptr首先,也不要根据 NULL 检查 ptr ,推导它并检查它是否指向 NUL ( '\0' ) 字符串终止符。

if (*ptr == '\0') {
  // this means all characters were parsed and converted to `long`
}
else {
  // this means either no characters were parsed correctly in which
  // case the return value is completely invalid
  // or
  // there was a partial parsing of a number to `long` which is returned
  // and ptr points to the remaining string
}

num > 1000001还需要是 num > 1000000

num < 0还需要是 num < 1

您还可以通过一些重组和逻辑调整将您的 if 语句序列压缩为仅 一个无效分支和一个正常分支。

关于c - 使用 strtol 验证 ANSI C 中的整数输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19148611/

相关文章:

c - fgets 不复制第一个字母

c# - 将C代码转换为C#,无法理解C中的某一行

java - 字符串频率搜索未找到所有单词

c - 将 n 个最低的数字存储在数组 C 中

mysql - 'b.Hostname' 中的未知列 'on clause'

C - 无法实现微型加密算法(意外值)

c - Windows - 同时等待事件和套接字

arrays - 将数组合并为一个字符串(matlab)

c - 为什么 strcpy 将垃圾字符附加到一小部分字符串的末尾?

c - 读取 sscanf() 中的可选空格