【发布时间】:2016-01-29 00:14:51
【问题描述】:
我正在尝试创建一个命令菜单,用户可以在其中执行任意数量的命令,直到按“q”结束循环。我想我有我需要做的一切,除了我中途意识到我的教授要求使用字符串。当我在程序中包含字符串时,我开始收到错误消息,说“无法将字符串转换为布尔值”,只要有一段时间或 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;
}
【问题讨论】:
-
当用户键入
q时,您并没有结束循环。在此处添加break语句。
标签: c++ string if-statement while-loop command