如何檢查 C/C++ 字串是否為 int?
有若干用於檢查字串是否是 int 的方法,其中一種方法是使用 isdigit() 來檢查字串。
以下是在 C++ 語言 中檢查字串是否是 int 的示例:
示例
#include<iostream> #include<string.h> using namespace std; int main() { char str[] = "3257fg"; for (int i = 0; i < strlen(str); i++) { if(isdigit(str[i])) cout<<"The string contains int\n"; else cout<<"The string does not contain int\n"; } return 0; }
輸出
以下是輸出
The string contains int The string contains int The string contains int The string contains int The string does not contain int The string does not contain int
在上述程式中,檢查字串的實際程式碼存在於 main() 函式中。使用內建方法 isdigit() 檢查字串的每個字元。如果字串字元是數字,它將列印該字串包含 int。如果字串包含字元或字母,它將列印該字串不包含 int。
for (int i = 0; i < strlen(str); i++) { if(isdigit(str[i])) printf("The string contains int\n"); else printf("The string does not contain int\n"); }
廣告