如何使用 C/C++ 查看输入是否为整数?
我们在这里了解如何查看给定的输入是整数字符串还是普通字符串。整数字符串将包含在范围 0 – 9 内的所有字符。解决方案非常简单,我们将逐一遍历每个字符,检查它是不是数字。如果它是数字,则指向下一个,否则返回 false 值。
示例
#include <iostream>
using namespace std;
bool isNumeric(string str) {
for (int i = 0; i < str.length(); i++)
if (isdigit(str[i]) == false)
return false; //when one non numeric value is found, return false
return true;
}
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
if (isNumeric(str))
cout << "This is a Number" << endl;
else
cout << "This is not a number";
}输出
Enter a string: 5687 This is a Number
输出
Enter a string: 584asS This is not a number
广告
数据结构
网络
关系数据库
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
JavaScript
PHP