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

Luk*_*aay 3 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);
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

谁能在正确的方向帮助我?显然,该错误与我的if(ptr!= NULL)条件有关,但据我所知这似乎是正确的。正如我所说,我已经看过以前与此类似的问题,并在答案中采纳了建议,但它似乎对我不起作用。因此,我认为最好根据自己的情况寻求帮助。

提前致谢!

goj*_*oji 5

您正在strtol以错误的顺序检查的结果,请ptr首先检查,也不要针对检查ptr NULL,推论它,并检查它是否指向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
}
Run Code Online (Sandbox Code Playgroud)

num > 1000001 也需要 num > 1000000

num < 0 也需要 num < 1

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