【发布时间】:2020-10-21 15:26:55
【问题描述】:
我正在学习 C++ 中的函数,我在 Tutorialspoint 上看到了这段代码,它告诉我们是否 输入是一个 int 或一个字符串。
Tutorialspoint 文章链接:https://www.tutorialspoint.com/cplusplus-program-to-check-if-input-is-an-integer-or-a-string
这是原始代码:
#include <iostream>
using namespace std;
//check if number or string
bool check_number(string str) {
for (int i = 0; i < str.length(); i++)
if (isdigit(str[i]) == false)
return false;
return true;
}
int main() {
string str = "sunidhi";
if (check_number(str))
cout<<str<< " is an integer"<<endl;
else
cout<<str<< " is a string"<<endl;
string str1 = "1234";
if (check_number(str1))
//output 1
cout<<str1<< " is an integer";
else
//output 2
cout<<str1<< " is a string";
}
原来的工作非常好,但我的代码要么只显示输出 1,要么只显示输出 2,无论你输入的是 int 还是 string。
我的代码:
注意:我的代码是在在线编译器上编写的。编译器链接:https://www.onlinegdb.com
#include <iostream>
using namespace std;
//the function which checks input
bool check(string s){
for(int i = 0; i < s.length(); i++)
if(isdigit(s[i]) != true)
return false;
return true;
}
//driver code
int main(){
string str = "9760";
if(check(str)){
//output 1
cout<<"Thanks! the word was " <<str;
}
else{
//output 2
cout<<"Oops! maybe you entered a number!";
}
}
执行我的程序时的输出:Thanks! the word was 9760
代码项目链接:https://onlinegdb.com/HkcWVpFRU
谢谢!
【问题讨论】:
-
i > s.length();看起来很不对劲 -
@UnholySheep 感谢您的帮助,但还是一样。
-
鉴于 C++ 标签检查此线程stackoverflow.com/q/8888748/6865932
-
@AustinParker 不,这不是一回事。如果您更改为
i < s.length(),您的代码会做错事,但它至少会根据输入做不同的事情。使用i > s.length(),它将始终返回 true。 -
@super 我的意思是同样的问题仍在发生。无论如何,现在已经解决了。感谢 SzyomonO!
标签: c++ string function int boolean