C++中的代码将不接受否并停止程序
Code in C++ will not accept no and stop the program
我已经尝试了很多事情,但我似乎无法弄清楚为什么该程序不会停止代码,如果您在提示重试或不重试时选择 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;
}
您的状况不是很好,应该是
if( (reboot == 'Y') || (reboot == 'y') )
{
goto start;
}
事实上,它总是计算为 true,因为"y"的计算结果为 true,而 true || anything
总是给出 true。
同样的事情也适用于yes_no
检查。
编辑 由于您遇到问题,我制作了一个简单的程序来更轻松地对其进行测试,这应该按预期工作:
#include <iostream>
using namespace std;
int main()
{
char yes_no;
while (true)
{
cout << "Enter 'N or 'n' to quitn";
cin >> yes_no;
if(yes_no == 'N'|| yes_no == 'n')
break;
}
return 0;
}
这2行看起来有点奇怪
if(yes_no == 'Y'||'y')
if(reboot == 'Y'||'y')
也许你的意思是在下面??
if(yes_no == 'Y' || yes_no == 'y')
if(reboot == 'Y' || reboot == 'y')
从代码不起作用的真正原因开始 - 运算符优先级和关联性:
reboot == 'Y'||'y'
总是返回true
,因为它被解析为 (reboot=='Y')||'y'
。如果要测试reboot
是否等于两个字符之一,请像这样测试:reboot=='Y'||reboot=='y'
.
这应该可以修复您的代码。虽然这里有一些建议:
- 不要使用
goto
语句。你可以使用循环(while
、for
或do while
)循环代码。 - 如果您使用的是
C++
,请使用std::string
来存储文本,然后可以使用text=="some Text"
而不是测试strcmp
的输出。 - 有关运算符优先级的未来参考,您可以随时查看维基百科。
相关文章:
- 为什么线程不接受此输入?
- C++程序不会从 Windows 控制台运行
- 程序不会执行函数 c++
- 为什么我的程序不能显示斐波那契级数?
- 函数不接受 X 参数,函数使用默认参数
- C++ boost::asio::ip::tcp::acceptor 有时不接受连接器?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 程序不向函数返回值
- 英特尔 TBB 程序不会终止,可能会误用参考计数器
- C++ 程序不会因为内存而终止
- B不接受8作为输入的是什么?C++
- 为什么一个简单的程序不能立即启动
- C++数组输入不接受一定数量的整数
- 我的C++程序不接受菜单后的输入
- 确定数的因数 当除数之和不大于该数时,程序将不接受大于 10000 的限制
- 程序不接受任何输入.第一次输入后,它会自动关闭
- C++中的代码将不接受否并停止程序
- C++ - 使用 cin 循环运行 while 后,程序不会再次接受输入
- 我在我的程序中添加了一个void函数,它不接受任何参数,现在我的程序在运行时只返回一个空白终端
- cin不接受输入,程序立即关闭