[英]How to use isdigit function to check whether a given multiple digit character is numeric or not?
如何使用C中的isdigit function來判斷給定的多位字符串是否為數字? 這就是我將 isdigit function 用於單個數字字符的方式。
#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);
}
}
然而,上面的代碼只適用於兩位數 integer,而不適用於三位數字 integer。看這個: Compiled Code SS
isdigit
function 不需要返回 boolean 0
或1
值。 如果字符不是數字,則指定返回零,如果是數字,則返回任何非零值。
以here使用的實現為例。 我們可以看到isdigit
返回2048
。
因為它返回該值,乘法將導致帶符號的 integer 算術溢出,進而導致未定義的行為。
相反,我建議您直接在條件中使用isdigit
,如果它返回0
,則打印消息並終止程序:
size_t length = strlen(num);
if (length == 0)
{
printf("String is empty\n");
return EXIT_FAILURE;
}
for (size_t i = 0; i < length; ++i)
{
if (isdigit(num[i]) == 0)
{
printf("Input was not a number\n");
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 '\0', 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.