How to Limit Input to Numbers Only

后端 未结 3 991
一生所求
一生所求 2021-01-06 11:21

I recently created a program that will create a math problem based on the user input. By entering either 1-4 the program can generate a problem or the user can quit by ente

3条回答
  •  失恋的感觉
    2021-01-06 12:15

    1. Read a single character
    2. If this character is a digit, use it.
    3. If this character wasn't a digit, goto 1.

    Actually, forget about step 2. Just check whether it was one of the digit characters you actually want ('1', '2', '3', '4', '5'):

    char choice;
    
    while(cin.get(choice)){
      if(choice == '5')
        break;
    
      switch(choice){
        default: printWrongCharacterMessage(); break;
        case '1': do1Stuff(); break;
        case '2': do2Stuff(); break;
        case '3': do3Stuff(); break;
        case '4': do4Stuff(); break;    
      }
    }
    

提交回复
热议问题