
在这里,我们将看到如何检查给定的输入是整数字符串还是普通字符串。整数字符串将包含在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
以上就是如何使用C/C++检查输入是否为整数?的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号