无法将字符串与while和if语句进行比较

时间:2015-10-29 01:12:01

标签: c++ string if-statement while-loop command

我正在尝试创建一个命令菜单,用户可以执行他/她想要的任意数量的命令,直到按“q”结束循环。我想我有我需要做的一切,除非我在中途意识到我的教授要求使用字符串。当我在程序中包含字符串时,我开始收到错误消息,说“无法将字符串转换为bool”,只要有一段时间或if语句。我该怎么做才能解决这个问题,让我的程序正常运行。提前致谢。

#include <iostream>
#include <string>
using namespace std;

int main()
{
    char option; 
    char number=0; 
    string s;
    string n;
    string p;
    string q;
    char number2; 

    cout << " Please enter a number: "<< endl; 
    cin >> number;

    do {

        cout << " Please enter a command: " << endl;
        cout << " s- square the number " << endl;
        cout << " n- add the number and (number +1) " << endl; 
        cout << " p- add the number and (number -1) " << endl; 
        cout << " q- quit" << endl; 
        cin >> option;

        if (option=s) {
            s= number*number;
            cout << "Square of this number is : " << s; 
        }
        else if ( option=n){
            number2= number+1;
            n= number+number2;
            cout << "Sum of" << number << "+" << number2 << "is: " << n;
        }
        else if (option=p) {
            number2= number-1;
            p= number+number2;
            cout << "Sum of" << number << "+" << number2 << "is" << p;
        }
        else if (option=q)
            cout << "Terminating Program";
    } while(option);
    return 0; 
}

2 个答案:

答案 0 :(得分:2)

您在<{1}}和if而不是比较分配

else if

应该是

if (option=s) {

请注意double =

此外,您需要在字符选择周围添加单引号(&#39;)。

这是一个经验丰富的开发人员常犯的错误。

这些声明

if (option=='s') {

应该都是char number=0; string s; string n; string p; string q; char number2;

int

答案 1 :(得分:0)

让我回答,好像我是谁将评估你的作业。你有几个问题:

  1. 系统会要求您使用string。避免同时使用charstring

    char option;      //  professor asked to use string: (-1) point
    
    string option;    //  ok
    
  2. 当您使用单个=时,就像在option="a"中一样,您将值<{1}}分配到变量"a" 。但在option语句中,您希望比较,因此您应该使用if-else比较运算符。另外,您无法将==char进行比较。

    string
  3. 您使用的是if(option = "a") // error: expression must have bool type: (-2) points if(option == 'a') // error: no operator "==" matches std::string == char; (-2) points if(option == "a") // ok ,但while(option)被声明为option,而不是char。当您输入bool时,请将此行替换为while(option!="q")以完成。

    q

    此外,当您从while(option); // error: expression must have bool type; (-2) points while(option != "q"); // GOOD! 声明中获取时,您的程序将完成;所以,尝试在此之后添加while消息。

  4. 您无需声明这么多变量("Terminating Program"snpq)。尝试在每个范围内使用临时变量,例如:

    number2
  5. 在您编写此代码的表单中,每次键入新选项时,您都会获得如下输出:

    if (option=="s") 
      {
        cout << "Square of this number is : " << number*number << endl;
      }
    else if ( option=="n")
      {
        int number2= number+1;
        cout << "Sum of " << number << "+" << number2 << " is : " << number+number2 << endl;
      }
    

    这对我来说很难看(-1分)。尝试在每Sum of 10+11 is : 21 Please enter a command: 行之后添加换行符(<< endl;)。

  6. 最后,如果我输入菜单中未列出的任何其他字母怎么办?我期待一条消息,如cout(-1分)。

相关问题