0

I am a beginner and i just shifted from Python to C++. I just want to write a code for taking input. It's something like. If user enter 1, print easy. if user enter 2, print Hard. Any other input other then 1 and 2 [including string], it will print wrong input and ask again for input until user choose either 1 or 2.

#include <iostream>
using namespace std;

int setdifficulty(){
    int level;
    level = 0;
    cout << "\nPlease enter the difficulty level\n'1' for easy\n'2' for hard \n";
    
    cin >> level; \* 0 if input is a string*\
    cout << "level is " << level;

    if (level==1){
        cout << "You selected easy level";
    }
    else if (level == 2){
        cout << "You selected Hard level";
    }
    else{
        cout << "Inappropiate choice! \nTry Again" << level;
        level = setdifficulty();
    }
    return level;
}

int main(){
    int level = setdifficulty();
    }

If we enter 1 or 2, it's working fine. But, if i enter 'fsdfsdf'. The variable named level takes value 2 and get stucked in infinite loop. please help me.

Rajeev R S
  • 25
  • 3
  • 1
    When `>>` fails to parse the required type out of the input, it sets a fail flag and will not allow further parsing until the error flag is `clear`ed. It's also recommended that you remove the bad input before reading it again and finding that it's still unparsable. The data is left in the stream because often after a failure you want to see if the input makes sense as a different type. – user4581301 Feb 07 '22 at 16:50
  • You need to get `std::cin` out of error state, after entering invalid values. – πάντα ῥεῖ Feb 07 '22 at 16:51
  • Your messages to `cout` should end with `\n`. In many implementations, you won't see the messages if they don't have a `newline` at the end. – Logicrat Feb 07 '22 at 16:53
  • Show actual code. Neither will the shown code compile nor has it a loop anywhere. – j6t Feb 07 '22 at 16:55
  • There's a reason why it's recommended to use `std::getline` to read input. And then use some other method to parse each line (for example `std::stoi`). – Some programmer dude Feb 07 '22 at 16:55
  • 1
    [This answer might help](https://stackoverflow.com/questions/10349857/how-to-handle-wrong-data-type-input#:~:text=4%20Answers&text=The%20reason%20the%20program%20goes,input%20from%20the%20input%20buffer.) – Axeon Thra Feb 07 '22 at 16:55

0 Answers0