C++ 与字符串文字进行比较会导致未指定的行为,错误 #include//include头文件 使用名称空间std; int main()//主体的开始 { int num;//声明整数 int control=1;//声明整数 while(control==1)//循环的开始,只要条件为true { 您可以在此处将整数与字符串进行比较num==“1”。相反,请使用num==1

C++ 与字符串文字进行比较会导致未指定的行为,错误 #include//include头文件 使用名称空间std; int main()//主体的开始 { int num;//声明整数 int control=1;//声明整数 while(control==1)//循环的开始,只要条件为true { 您可以在此处将整数与字符串进行比较num==“1”。相反,请使用num==1,c++,string,menu,C++,String,Menu,错误在于您将int(num)与字符串文本(如“1”)进行比较。此特定字符串文本具有类型常量字符[2],它将衰减为常量字符*,因此出现编译器错误 例如,您需要将数字与数字进行比较 #include <iostream> //include header files using namespace std; int main () //start of main body { int num; //declaring integer int control=1; //decla

错误在于您将
int
num
)与字符串文本(如
“1”
)进行比较。此特定字符串文本具有类型
常量字符[2]
,它将衰减为
常量字符*
,因此出现编译器错误

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

#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;
}


}

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

if(num==1)

不是

if(num==“1”)

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


<> > C++编译器会给你错误,因为你不能比较两种不同的数据类型。在比较中,请参阅

> p>你不需要<代码>菜单是String 类型,因为你要求用户输入整数。 简单使用

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


正在与字符串比较的整数:)


不允许,顺便说一句,我认为您想要的不是“num”,而是“menu”,它是一个字符串?

首先,您的num未初始化。 当您要更改此项时,还可以将比较从
num==“1”
num==1

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


除了这是非常好的代码之外,我会选择4)

如果(num==1)
,而不是
如果(num==“1”)
(欢迎使用stackoverflow。请阅读常见问题解答,对于未来的问题,请记住,如果您(1),人们将更有可能帮助您做一个简短的例子来说明你的意思-你可以减少80%的代码,但它仍然会显示问题,(2)用行号提供准确的错误消息,并在代码中标记相关行,这样我们就不必逐行检查。)可能还想在某个时候为
num
分配一些内容。谢谢大家,我已经对num==“1”的比较进行了更改对于num==1,并已取出字符串,并将输入存储在num变量中,我还取出了else语句,因为它不需要,但我尚未初始化num变量,但代码仍在执行。这是一个很好的做法吗?@user2204993请对代码进行这些更改,这样我们就可以看到您做了什么,以及您现在的问题是什么
if (num == 1) 
if (num == "1")
num == "1"