我认为我的代码很好,但它在 cin a 之后停止并且没有进一步?

I think my code is good but it stops after cin a and dont go further?

本文关键字:之后 进一步 cin 代码 我的 很好      更新时间:2023-10-16

所以这是代码。 请告诉我此代码中出了什么问题,为什么服用 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。更准确地说,字符串存储在变量astring常量中。

以下方法应该有效:

#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...
}