C++中的代码将不接受否并停止程序

Code in C++ will not accept no and stop the program

本文关键字:程序 不接受 代码 C++      更新时间:2023-10-16

我已经尝试了很多事情,但我似乎无法弄清楚为什么该程序不会停止代码,如果您在提示重试或不重试时选择 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 语句。你可以使用循环(whilefordo while)循环代码。
  • 如果您使用的是 C++ ,请使用 std::string 来存储文本,然后可以使用 text=="some Text" 而不是测试 strcmp 的输出。
  • 有关运算符优先级的未来参考,您可以随时查看维基百科。