c++ - 开关量问题:开关量不是整数,无法将 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)
解决方案
错误说,开关中的测试必须是整数,但你有一个字符串。
此外,您对string
哪些是多个字符(例如“abc”)和char
哪些是单个字符(例如“a”、“b”或“c”)感到困惑。
要修复使用,只需更改
string c;
至
char c;
之所以有效,是因为您只需要一个字符,c
因此char
是适当的类型,还因为char
在 C++ 中是一种整数,因此可以在开关中使用。
你这里有另一个错误
cout<<"Type Yes or No";
cin>>d;
if(d="yes"){
第一个问题是您要求用户输入Yes
orNo
但您测试"yes"
,"Yes"
并且"yes"
不是同一个字符串。
第二个问题是相等的检验==
不是=
。=
用于赋值,这与测试相等性不同。
推荐阅读
- asp.net - 从 CSV 文件导入日期和时间的两列之间的差异
- npm - npm install 失败,在某些服务器上找不到某些包
- python - PySFTP/Paramiko 异常泄漏到标准错误中
- javascript - 平移 3D 点
- python-3.x - python - sqllite - 这是什么对象?0- 可下标
- javascript - 如何获取所有 Slide-Toggle 元素的 ID 和值
- flutter - 在颤动中处理复选框状态
- android - google play 需要多长时间才能更新我的应用页面中列出的类似应用?
- flutter - Flutter - 屏幕拖动边缘无意返回页面
- node.js - Req.params 显示数据,但 req.params.variable_name 显示未定义