Search code examples
c++loopsreboot

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


I have tried many things and i can not seem to figure out why this program will not stop the code if you select N when it prompts to try again or not.

I feel as though i had this working earlier, but i can not find any code from when it was working, and i see no reason this should not work. Can anyone help out?

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

Solution

  • Your condition is not well formed it should be

    if( (reboot == 'Y') || (reboot ==  'y') )
    {
        goto start;
    }
    

    As it is, it always evaluates to true since 'y' evaluates to true and true || anything always gives true.

    Same thing applies to yes_no check.

    EDIT Since you are having trouble, I made a simple program to test it more easily, this should work as expected:

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