C语言 如何使用isdigit函数来检查给定的多个数字字符是否为数字?



如何在C中使用isdigit函数来检查给定的多位数字符串是否为数字?下面是我对一个单位数字符使用isdigit函数的方法。

#include<stdio.h>
#include<cs50.h>
#include<ctype.h>
int main()
{
char c = get_char("Enter a single character:");
int a = isdigit(c);
if ( a != 0)
{
printf("%c is an integer n", c);
}
else
{
printf("%c is not an integer n",c);
}
}

现在,我想检查多位数字符(例如。92年,789年)。这是我的代码

#include<stdio.h>
#include<cs50.h>
#include<string.h>
#include<ctype.h>
int main()
{
string num = get_string(" Enter a number:");
int final = 1;
for(int i =0; i< strlen(num); i++)
{
// final = final * isdigit(num(i));
final*= isdigit(num[i]);
}
if(final!=0)
{
printf("%s is an integer.n", num);
}
else
{
printf("%s is not an integer.n", num);
}
}

但是,上面的代码只适用于两位整数,而不适用于三位整数。看到这个:已编译代码SS

isdigit函数不需要返回布尔值01。如果字符不是数字,则返回0,如果字符是数字,则任何非零值。

以这里使用的实现为例。我们可以看到isdigit返回2048

由于返回该值,乘法运算将导致有符号整数算术溢出,进而导致未定义行为

相反,我建议您直接在条件中使用isdigit,如果它返回0,则打印消息并终止程序:

size_t length = strlen(num);
if (length == 0)
{
printf("String is emptyn");
return EXIT_FAILURE;
}
for (size_t i = 0; i < length; ++i)
{
if (isdigit(num[i]) == 0)
{
printf("Input was not a numbern");
return EXIT_FAILURE;
}
}
// Here we know that all characters in the input are digits

您可以简单地将乘法运算替换为&…一旦出现非数字并且isdigit()返回0(即false),则标志变量将保持false

您可能需要考虑将操作组合成紧凑的代码,如以下所示:

#include <stdio.h>
#include <ctype.h>
#include <cs50.h> // less "generic" that the others
int main( void ) {
string num = get_string(" Enter a number:");
int i = 0;
while( isdigit( num[i] ) ) i++; // loop fails on '', too
if( i == 0 || num[i] ) // empty string or did not reach its end
printf( "%s is NOT an integer.n", num );
else
printf( "%s is an integer.n", num );
return 0;
}

相关内容

最新更新