您好,欢迎访问一九零五行业门户网

如何使用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: 5687this is a number
输出enter a string: 584assthis is not a number
以上就是如何使用c/c++检查输入是否为整数?的详细内容。
其它类似信息

推荐信息