如何在 C++ 中检查输入是否为数字?
c++server side programmingprogramming
在这里我们将看到如何检查给定的输入是数字字符串还是普通字符串。数字字符串将包含 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; //当发现一个非数字值时,返回 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