我认为我的代码很好,但它在 cin a 之后停止并且没有进一步?
I think my code is good but it stops after cin a and dont go further?
所以这是代码。 请告诉我此代码中出了什么问题,为什么服用 cin>>a 后会停止;
#include <iostream>
using namespace std;
int x;
int y;
int main(){
cout<<"What do you want to do:-"<<endl<<"add"<<endl<<"sub"<<endl<<"mul"<<endl<<"div"<<endl;
string a;
cin >> a;
if('a' =='add')
{
cout<<"working"<<endl;//this was used to check whether was working or not but it didn't
cin>>x;
cin>>y;
cout<< x+y <<endl;
}
if('a' =='sub')
{
cout<<"working"<<endl;
cin>>x;
cin>>y;
cout<< x-y <<endl;
}
if('a' =='mul')
{
cout<<"working"<<endl;
cin>>x;
cin>>y;
cout<< x*y <<endl;
}
if('a' =='div')
{
cout<<"working"<<endl;
cin>>x;
cin>>y;
cout<< x/y <<endl;
}
return 0;
}
所以它完美地构建。我正在使用日食IDE。 谢谢
你编码退出是因为所有这些if
语句都是错误的。例如,将字符a
与多字符常量div
进行比较。你真正想做的是比较strings
。更准确地说,字符串存储在变量a
和string
常量中。
以下方法应该有效:
#include <iostream>
using namespace std;
int x;
int y;
int main(){
cout<<"What do you want to do:-"<<endl<<"add"<<endl<<"sub"<<endl<<"mul"<<endl<<"div"<<endl;
string a;
cin >> a;
if(a =="add")
{
cout<<"working"<<endl;//this was used to check whether was working or not but it didn't
cin>>x;
cin>>y;
cout<< x+y <<endl;
}
if(a =="sub")
{
cout<<"working"<<endl;
cin>>x;
cin>>y;
cout<< x-y <<endl;
}
if(a =="mul")
{
cout<<"working"<<endl;
cin>>x;
cin>>y;
cout<< x*y <<endl;
}
if(a =="div")
{
cout<<"working"<<endl;
cin>>x;
cin>>y;
cout<< x/y <<endl;
}
return 0;
}
你看:
a
通过删除 ' 和string
常量需要 " " 而不是 ' 来访问。
我希望这有帮助! 问候
尝试使用标头中存在的strcmp
函数来比较if
语句中的字符串string.h
。
if(strcmp(a, "add") == 0) {
// Addition code here...
}
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 在类定义之后定义一个私有方法
- 在循环C++中指定字符串之后,不会打印该字符串
- C++宏忽略之后的内容
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- strncpy之后的char数组的错误行为
- 计算十进制 c++ 之后的数字
- "x += x--"之后的 x 是什么?
- 类的前向声明之后的类成员函数定义,在类声明之前
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- execlp() 在 fork() 之后无法正常工作
- 我认为我的代码很好,但它在 cin a 之后停止并且没有进一步?
- 如何在MISRA C++之后实施CRTP
- 在 OpenCV 的 namedWindow 之前或之后初始化 Tesseract
- 检测到堆损坏:在正常块 c++ 动态 2D 数组之后
- C++ 如果在 if 为 true 之后运行,为什么还会这样做
- 在 fork() 之后,我在我的程序中不断得到相同的 pid
- OpenSSL C API:如何在程序exec()之后恢复TLS连接?
- 了解在返回值之前和之后使用 EAX 的函数调用
- 在 C++20 之前和之后初始化 std::atomic