【问题标题】:Why do these perfectly similiar codes not work?为什么这些完全相似的代码不起作用?
【发布时间】: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 &gt; s.length(); 看起来很不对劲
  • @UnholySheep 感谢您的帮助,但还是一样。
  • 鉴于 C++ 标签检查此线程stackoverflow.com/q/8888748/6865932
  • @AustinParker 不,这不是一回事。如果您更改为i &lt; s.length(),您的代码会做错事,但它至少会根据输入做不同的事情。使用i &gt; s.length(),它将始终返回 true。
  • @super 我的意思是同样的问题仍在发生。无论如何,现在已经解决了。感谢 SzyomonO!

标签: c++ string function int boolean


【解决方案1】:

您正在检查 char 是否为数字,如果是则返回 false,您应该将其更改为

bool check(string s){
    for(int i = 0; i < s.length(); i++)
        if(isdigit(s[i])
           return false;
return true;     
}

旁注,如果您想检查是否为 false,您可以使用 (!bool) 而不是 (bool != true) 它看起来更干净

【讨论】:

  • 完美说明正确命名的重要性:check ...什么?我在 if (check(str)) 发现了这个错误,你在函数内部发现了它:我们是对的,也是错的,这种模棱两可表明这不是自记录代码。
  • @AustinParker 检查字符是否为数字并返回布尔值。如果您对某个功能有任何疑问,我推荐 cppreference 页面。 en.cppreference.com/w/cpp/string/byte/isdigit
  • @AustinParker 该函数的命名约定是错误的。我们看到一个名为check 的函数,但它检查的是什么?它应该命名为checkIfStringContainsNumber。有时最好使用更长的名称以自我解释。
  • @AustinParker 您的代码(尤其是您的函数)在做什么并不明显:将其命名为is_digitrepresents_digit 或任何明确的名称都可以使您免于此错误。正确命名函数、变量……是一项非常重要的技能,因为它可以使程序更清晰,从而使错误更难隐藏。
  • @AustinParker 没有问题。它的工作原理完全一样,但!isdigit(s[i]) 更短,更好看,相信我,每个阅读它的程序员都会得到! 在开始时的含义
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-18
相关资源
最近更新 更多