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

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.