使用字符串输出特定答案

时间:2014-01-02 06:57:20

标签: c++

假设我必须输出一个程序,当我输入yes时它应该显示再试一次如果我输入no它应该说thankyou 我已经制作了这样的程序,请帮助我修改这个程序,因为它不起作用

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string x;
    x="yes"||"no";
    while(x!="0")
{
    cout<<"Please enter your choice=  "<< x << endl;
    cin>>x;
 if (x="yes")
    {cout<< "Please enter again";}
 else if (x="no")
    {cout<< "Thankyou";}
}
 return 0;
} 

2 个答案:

答案 0 :(得分:1)

这里有几个问题:

x="yes"||"no";

这基本上没有效果。你正在x下面阅读。

您应该将while(x!="0")替换为while(true)以获得无限循环,直到获得所需的结果。

然后x = "yes"x = "no" 分配字符串。您想使用==进行比较。

如果更改为while(true),则必须将break;放在“no”-branch中才能退出循环。

答案 1 :(得分:0)

您的代码应为:

#include<iostream>
#include<string>

using namespace std;

int main()
{
    string x;
    x="yes or no";
    while(true)
    {
        cout << "Please enter your choice=  " << x << endl;

        cin >> x;

        if(x == "yes")
        {
           cout << "Please enter again";
        }
        else if(x == "no")
        {
           cout << "Thank you";
           break;
        }
     }

     return 0;
}

单个=运算符是赋值运算符,而双==运算符是比较运算符。 Here是一个进一步解释运算符的教程。另外我认为你写了这一行 - x="yes"||"no";认为它意味着x="yes or no";但是在组合条件如||时使用了析取if(x == "yes" || x == "no")运算符。