While condition: How to allow comparison between non-integer/double user input and integer limits

Objective: Run a while loop that will repeat until the user inputs an integer between 1-3 (inclusive). So if an integer that is smaller than 1 or bigger than 3 is inputted or any character or string is inputted, the loop repeats.

My noob knowledge: I know how to compare user input when it is an integer, but when it is a char or string datatype input all I get is an infinite loop. Plus I declared the inputtable variable as an integer, so not sure how to go on about this.

I’ve done some Google searches but can’t seem to find a question similar enough to mine.
Advice is highly appreciated :slight_smile:

Code below:

int Decision1 = 4;

while ( Decision1 < 1 || Decision > 3)
      {
        std::cout << "Enter answer here: ";
        std::cin >> Decision1;
        std::cout << "\n\n";
      }

Once that char was sent to Decision instead of an int, your stream(cin) entered a fail state. This causes your program to stop prompting you for new input and ‘freefall’ through the loop infinitely.
We need to do a few things to fix this

  1. Check our input before we use it.
    The best way to do this is to add a clause to your while loop
    while(d < 1 || d > 3 || cin.fail()) { cin.clear() cin.ignore(10000,"\n")
    }
    clear gets rid of the fail state that cin is in and ignore gets rid of the ‘bad’ input in the stream - note that this will clear 10,000 ‘bad’ characters. It is unlikely your user entered more bad input than that but they could. There are ways to handle this such as std::numeric_limits::max but that’s a bit advanced
    `
    There is a concept called “Garbage in, Garbage out” If your user gives you garbage input, your program will generate garbage.
    You need to always make sure your user didn’t give you garbage, and if they did you need to take that garbage out.
1 Like

Hi, thanks for your input!
I’m not sure if I incorporated your code correctly in mine, I got an error when compiling it.

int Decision1 = 4;

while ( Decision1 < 1 || Decision1 > 3 || cin.fail() )

  {

    std::cout << "Enter answer here: ";

    std::cin >> Decision1;

    std::cout << "\n\n";

    cin.clear();

    cin.ignore(1000,"\n");

  }

error:
Text_Adventure.cpp
Text_Adventure.cpp(39): error C2664: ‘std::basic_istream<char,std::char_traits> &std::basic_istream<char,std::char_traits>::ignore(std::streamsize,int)’: cannot convert argument 2 from ‘const char [2]’ to ‘int’
Text_Adventure.cpp(39): note: There is no context in which this conversion is possible
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29333\include\istream(476): note: see declaration of ‘std::basic_istream<char,std::char_traits>::ignore’

you need to include <iostream>