我已经尝试了很多东西,但我似乎无法弄清楚为什么如果你提示再次尝试时选择N,这个程序不会停止代码。
我觉得好像我之前有这个工作,但我找不到任何代码,因为它工作,我认为没有理由这不起作用。任何人都可以帮忙吗?
#include <iostream>
using namespace std;
int main ()
{
char color[10];
char reboot, yes_no;
start:
cout << "What color is the light?\n";
cin >> color;
//if the light is Green
if (!strcmp(color, "green")) {
cout << "The light is Green, you may go ahead and drive thru the intersection.\n";
} else if (!strcmp(color, "Green")) {
cout << "The light is Green, you may go ahead and drive thru the intersection.\n";
//if the light is Yellow
} else if (!strcmp(color, "yellow")) {
cout << "The light is Yellow, safely stop at the intersection, or proceed thru.\n";
} else if (!strcmp(color, "Yellow")) {
cout << "The light is Yellow, safely stop at the intersection, or proceed thru.\n";
//if the light is Red
} else if (!strcmp(color, "red")) {
cout << "The light is Red, you need to stop.\n";
} else if (!strcmp(color, "Red")) {
cout << "The light is Red, you need to stop.\n";
}
//non recognised input
else{
cout << "\nYour input was not recognised...Would you like to restart? (Y/N)\n";
cin >> yes_no;
if(yes_no == 'Y'||'y'){
goto start;
}
}
//restart program
restart:
cout << "\nWould you like to run the program again? (Y/N)\n";
cin >> reboot;
if(reboot == 'Y'||'y'){
goto start;
}
return 0;
}
答案 0 :(得分:2)
你的病情不是很好,应该是
if( (reboot == 'Y') || (reboot == 'y') )
{
goto start;
}
实际上,它总是计算为true,因为'y'的计算结果为true,true || anything
总是给出为真。
同样的事情适用于yes_no
检查。
编辑由于您遇到了麻烦,我制作了一个简单的程序来更轻松地测试它,这应该按预期工作:
#include <iostream>
using namespace std;
int main()
{
char yes_no;
while (true)
{
cout << "Enter 'N or 'n' to quit\n";
cin >> yes_no;
if(yes_no == 'N'|| yes_no == 'n')
break;
}
return 0;
}
答案 1 :(得分:0)
这两行看起来有点奇怪
if(yes_no == 'Y'||'y')
if(reboot == 'Y'||'y')
也许你想在下面而不是??
if(yes_no == 'Y' || yes_no == 'y')
if(reboot == 'Y' || reboot == 'y')
答案 2 :(得分:0)
从您的代码不起作用的真正原因开始 - 运算符优先级和关联性:
reboot == 'Y'||'y'
始终返回true
,因为它被解析为(reboot=='Y')||'y'
。如果您想测试reboot
是否等于两个字符之一,请按以下方式进行测试:reboot=='Y'||reboot=='y'
。
那应该修复你的代码。虽然这里有一些建议:
goto
声明。您可以使用循环(while
,for
或do while
)循环代码。C++
,使用std::string
存储文字,则可以使用text=="some Text"
代替测试strcmp
的输出。