如何在C ++中检查输入是否为数字?
在这里,我们将看到如何检查给定输入是数字字符串还是普通字符串。数字字符串将包含0到9范围内的所有字符。解决方案非常简单,我们将简单地逐个检查每个字符,然后检查它是否为数字。如果是数字,则指向下一个,否则返回假值。
示例
#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
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志