简体   繁体   中英

Wrong input in nested while loop

I don't no how to handle wrong input. I made an nested while loop, because if I only use the If statement and the input is wrong, it jumps to the beginning of the first while loop and not to "Do you wish to continue?". If I use a nested while loop, it somehow won't finish, even though the bool condition is satisfied. Please help.

Original Code on Github

 while((end2 == false))
    {
        cout << endl;
        cout << "Do you wish to continue? (Y / N)" << endl;

        
        char go_on;
        cout << "Your choice: ";
        cin >> go_on;
        cout << endl;


        if((go_on != 'Y') && (go_on != 'y') && (go_on != 'N') && (go_on != 'n'))
        {
            cout << "Invalide input! Choose between Y and N" << endl;
            continue;
        
        }

        if((go_on == 'Y') || (go_on == 'y'))
        {
            end2 == true;
            end  == false;
        } 
        
        if((go_on == 'N') || (go_on == 'n'))
        {
            end2 = true;
            end  == true;
        }   
        
}

It may be a lot simpler to create a function

bool check_continue() {
    while(true) {
        // get your input
        if((go_on == 'Y') || (go_on == 'y'))
            return true;
    
        if((go_on == 'N') || (go_on == 'n'))
            return false;
    }
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM