如何检查 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");
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP