我认为我的代码不错,但是在cin a之后就停止了,不要再走了?

时间:2018-10-14 06:39:28

标签: c++

这是代码。 请告诉我这段代码有什么问题,为什么在服用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。 谢谢

2 个答案:

答案 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...
}