首页 > 解决方案 > 开关量问题:开关量不是整数,无法将 basic_string' 转换为 'bool'

问题描述

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

#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)

标签: c++if-statementswitch-statementcalculator

解决方案


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

此外,您对string哪些是多个字符(例如“abc”)和char哪些是单个字符(例如“a”、“b”或“c”)感到困惑。

要修复使用,只需更改

string c;

char c;

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

你这里有另一个错误

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

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

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


推荐阅读