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