1

I have a program which asks the user to input an integer in the range [0,2]. I used the following link as a guide.

Good input validation loop using cin - C++

However, when the user presses enter without inputting data the cursor simply goes to the next line in the command prompt whereas I would prefer it to prompt the user to enter a valid number. Does prompting the user in this case make sense, or is there a reason not to implement validation as single line input to begin with? In the case of strings I would use getline to solve this, should I use that somehow in this case? Here is my code, based on the above link:

#include <iostream>

int main()
{
    int answeredNumber;
    while(1)
    {
        std::cout << "Enter your answer: ";
        if(std::cin >> answeredNumber && answeredNumber >= 0 && answeredNumber <= 2)
        {
            break;
        }
        else
        {
            std::cout << "Please enter a valid answer: " ;
            std::cin.clear();
          std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }
    system("pause");
}
Community
  • 1
  • 1
Average
  • 165
  • 2
  • 8

2 Answers2

3

That's because getting an integer with cin will skip leading whitespace, including a newline. There's no easy way around that.

If you want line-based input, you can get your input value as a string and then interpret that:

#include <iostream>
#include <sstream>
#include <string>

int main (void) {
    std::string inputLine;
    int answer;
    std::cout << "Enter your answer: ";
    while(1) {
        getline (std::cin, inputLine);
        std::stringstream ss (inputLine);
        if ((ss >> answer))
            if ((answer >= 0) && (answer <= 2))
                break;
        std::cout << "No, please enter a VALID answer: " ;
    }
    std::cout << "You entered " << answer << '\n';
    return 0;
}
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

The other answer specifies the problem. However, a slight modification to your code I think will solve your immediate problem:

int answeredNumber = std::cin.get() - '0';
if(answeredNumber >= 0 && answeredNumber <= 2)

std::cin with the >> operator receives formatted data, you will need to use get() and other functions to receive unformatted data.

Jesse Good
  • 50,901
  • 14
  • 124
  • 166
  • Doesn't `get` get a _character_ then cast it to an integer? I think you may need to turn that into a real value (by subtracting '0' for example). – paxdiablo May 22 '12 at 05:09