【问题标题】:This string comparison isn't working此字符串比较不起作用
【发布时间】:2015-10-25 02:44:32
【问题描述】:

所以当我输入我想要使用的月份时,例如 12 月,并且我将 722 作为小时数,程序会说:“您输入的小时数不能超过第 720 个月”。有没有办法解决?我不想每个月都做if语句,我觉得有一种更简单的方法。这也是我的第一个大学课程

int userPackage, userHours; //Declaring integer variables
double savings, savings2, total; //Declaring double value
string userMonth;
cout<<"\tHello.\nEnter the number of the package you have\n1) Package A\n2) Package B\n3) Package C\n"; //Prompts the user for their package in a menu like fashion
cin>>userPackage; //gets package
if(userPackage > 3 || userPackage < 1) //Error output for numbers that don't match packages
{
    cout<<"Error, invalid choice";
    return 0;
}

cout<<"Enter the number of hours you have been online."; //Propmts the user for the number of hours they've been online
cin>>userHours; //gets hours
cout<<"Enter the month (by name): ";
cin>>userMonth;
cout<<"\n";
if(userMonth == "January","March","May","July","August","October","December")
{
    if (userHours > 744)
    {
        cout<<"The amount of hours you entered cannot exceed the amount of hours within the month 744";
        return 0;
    }
}
if(userMonth == "April", "June", "September", "November");
{
    if(userHours > 720)
    {
        cout<<"The amount of hours you entered cannot exceed the amount of hours within the month 720";
        return 0;
    }
}
if(userMonth == "February");
{
    if (userHours > 672)
    {
        cout<<"The amount of hours you entered cannot exceed the amount of hours within the month 672";
        return 0;
    }   
}

【问题讨论】:

  • userMonth == "January","March","May","July","August","October","December" 这不是您将字符串与多种可能性进行比较的方式。您可以将这些字符串存储在静态 const 数组或集合中,并查找字符串是否在其中。
  • if(userMonth == "April", "June", "September", "November"); 我敢打赌,您从未在任何声称教授 C++ 的书籍、教程、网站等中看到过这样的 if 声明。那么你是怎么想到这个的呢?

标签: c++ string if-statement compare string-comparison


【解决方案1】:

if(userMonth == "January","March","May","July","August","October","December")

这并不像您认为的那样做(即,它userMonth 与每个字符串进行比较。您可能打算编写的语句(假设您也想使用else if 即使您的代码没有):

if (userMonth == "January" ||
    userMonth == "March" ||
    userMonth == "July" ||
    userMonth == "August" ||
    userMonth == "October" ||
    userMonth == "December")
{
    ...
}
else if (userMonth == "April" ||
    userMonth == "June" ||
    userMonth == "September" ||
    userMonth == "November")
{
}
else if (userMonth == "February")
{
}

注意:这些也是区分大小写的比较(即,“一月”不等同于“一月”或任何其他大小写差异),最好将所有内容都转换为小写或全部大写。

if(userMonth == "April", "June", "September", "November");
// problematic trailing semi-colon ^

这将结束if 语句并且无条件执行下一个块。因此,当输入 722 时,它总是大于 720 并且您会收到您所看到的消息。

“二月”的 if 逻辑中也有同样的错误。

【讨论】:

  • 您的措辞暗示if(userMonth == "January","March", &lt;etc&gt; 等同于if (userMonth == "January" || userMonth == "March" || &lt;etc&gt;,但实际上并非如此。
  • 感谢您的帮助。我尝试在网上查找解决方案,但并不真正知道如何表达我的问题。我还在学习所有的术语。但是,是的,它奏效了,我能够继续编写程序。非常感谢!
猜你喜欢
  • 2011-09-20
  • 2014-04-03
  • 2012-01-22
  • 2017-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多