Average
Average

Reputation: 165

How do I implement single line integer type command line input validation using cin?

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

Upvotes: 1

Views: 364

Answers (2)

Jesse Good
Jesse Good

Reputation: 52365

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.

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881683

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

Upvotes: 3

Related Questions