Home > OS >  Wrong input in nested while loop
Wrong input in nested while loop

Time:04-07

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

CodePudding user response:

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;
    }
}  
  •  Tags:  
  • c
  • Related