【问题标题】:Switch Quantity problem: switch quantity not an integer and could not convert basic_string’ to ‘bool’开关量问题:开关量不是整数,无法将 basic_string' 转换为 'bool'
【发布时间】:2026-01-16 10:05:01
【问题描述】:

我正在尝试创建一个计算器,但发生了这种情况.. 这是我的代码。请帮我解决它并给出一些解释:

#include <iostream>

using namespace std;

int main()
{
    int a;
    int b;
    string c;
    string d;
    cout<<"Enter No. 1: ";
    cin>>a;
    cout<<"Enter Operation: ";
    cin>>c;
    cout<<"Enter No. 2: ";
    cin>>b;
    cout<<"So you want me to solve this: ";
    cout<<a<<c<<b;
    cout<<"Type Yes or No";
    cin>>d;
    if(d="yes"){
        switch(c)
    {
        case '+':
            cout << a+b;
            break;

        case '-':
            cout << a-b;
            break;

        case '*':
            cout << a*b;
            break;

        case '/':
            cout << a/b;
            break;
    }
    }
        else{
                return 0;
        }
    
    

}

这是编译时的代码错误,请修复此代码 ima noob:

main.cpp: In function ‘int main()’:
main.cpp:21:9: error: could not convert ‘d.std::basic_string<_CharT, _Traits, _Alloc>::operator=, std::allocator >(((const char*)"yes"))’ from ‘std::basic_string’ to ‘bool’
     if(d="yes"){
        ~^~~~~~
main.cpp:22:17: error: switch quantity not an integer
         switch(c)

【问题讨论】:

  • if(d="yes") 应该是 if(d=="yes")。而且你不能在switch 中使用std::string。看来您希望 c 属于 char 类型。
  • 你的“礼物”完全离题,应该删除。
  • 如果有疑问,请拨打tour 并查看How to Ask

标签: c++ if-statement switch-statement calculator


【解决方案1】:

错误说明了,开关中的测试必须是整数,但你有一个字符串。

您还对多个字符(例如“abc”)的string 和单个字符(例如“a”、“b”或“c”)的char 感到困惑。

要修复使用,只需更改

string c;

char c;

之所以有效,是因为您只需要c 中的单个字符,因此char 是合适的类型,还因为C++ 中的char 是一种整数,因此可以在开关中使用。

这里还有一个错误

cout<<"Type Yes or No";
cin>>d;
if(d="yes"){

第一个问题是您要求用户输入YesNo,但您测试的"yes""Yes""yes" 不是同一个字符串。

第二个问题是相等的测试是== 而不是== 用于赋值,与测试相等性不同。

【讨论】:

    【解决方案2】:

    这里有两个主要问题:

    1. 您在开关中提供std::string,这是不可能的。您只能将一个字符或一个整数传递给它。您可以将其转换为 char 类型。

    2. 条件行出现一个逻辑错误(注意注释):

      if(d="yes") // it should be d == "yes"
      

    【讨论】:

      最近更新 更多