这是代码。 请告诉我这段代码有什么问题,为什么在服用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;
}
所以它完美构建。我正在使用Eclipse IDE。 谢谢
答案 0 :(得分:2)
您的代码退出是因为所有这些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
常量需要“”而不是''。
我希望这会有所帮助! 问候
答案 1 :(得分:0)
尝试使用strcmp
标头中的string.h
函数来比较if
语句中的字符串。
if(strcmp(a, "add") == 0) {
// Addition code here...
}