与字符串文字比较导致未指定的行为,错误

时间:2013-03-24 17:09:48

标签: c++ string menu

#include <iostream> //include header files

using namespace std;

int main () //start of main body

{

int num; //declaring integer

int control=1; //declaring integer

while(control==1)//start of loop, as long as condition is true
{
    cout << "Press 1 for coffee" << endl; //writes to standard o/p
    cout << "Press 2 for tea" << endl;
    cout << "Press 3 for hot chocolate" << endl;
    cout << "Press 4 for soft drink" << endl;
    cout << "Press 5 to exit" << endl;
    cin >> num;


if (num == 1) //code to execute if integer = 1
{
    cout << "coffee selected" << endl;
}
else if (num == 2) //code to execute integer = 2
{
    cout << "tea selected" << endl;
}
else if (num == 3) //code to execute if integer = 3
{
    cout << "hot chocolate selected" << endl;
}
else if (num == 4) //code to execute if integer = 4
{
    cout << "soft drink selected" << endl;
}
else if (num == 5) //code to execute if integer = 5
{
    cout << "Exit Program" << endl;
    control=0;
}


}

}

这是我的修改后的代码。但是我不确定初始化num整数,所以我把它留了出来但代码仍然执行并正常工作。

6 个答案:

答案 0 :(得分:3)

错误在于您将intnum)与字符串文字(例如"1")进行比较。此特定字符串文字的类型为const char[2],它会衰减到const char*,因此编译错误。

您需要将数字与数字进行比较,例如

if (num == 1) { .... }

答案 1 :(得分:2)

您要将整数与字符串num == "1"进行比较。相反,请使用num == 1

答案 2 :(得分:2)

您正在尝试将数字与字符串文字进行比较。 一个好计划。尝试

if(num==1)

if(num=="1")

其次,num未定义。尝试为其设置一个值。

C ++编译器会为您提供错误,因为您无法比较两种不同的数据类型。阅读有关比较的更多信息here

答案 3 :(得分:2)

由于要求用户输入整数,因此您不需要menustring类型。 只需使用

if (num == 1) 

if (num == "1")

答案 4 :(得分:1)

与字符串比较的整数:)

num == "1"

不允许,顺便说一句,我认为而不是“num”而是你想要的“菜单”,这是一个字符串?

答案 5 :(得分:1)

首先,你的数字未初始化。 当你改变这个,然后改变num == "1"的比较 至  num == 1

目前,当您执行menu时,您将输入放入getline (cin, menu, '\n');变量中,因此如果要在num中存储输入,则必须更改此项。

除此之外是漂亮的代码,我会选择4)

相关问题