djaszak
djaszak

Reputation: 125

Validate console input in c++

I wrote the code below which works in a case of valid input

char input[100];
cin.getline(input, sizeof(input));
stringstream stream(input);
while (stream.rdbuf()->in_avail() != 0) {
    int n;
    stream >> n;
    numbers.push_back(n);
}

but fails when I put something instead of a number. How can I hadle wrong intput(e.g. any letter)?

Upvotes: 1

Views: 1388

Answers (1)

paweldac
paweldac

Reputation: 1184

For example:

bool is_number(const std::string& s)
{
    return !s.empty() && std::find_if(s.begin(), 
        s.end(), [](char c) { return !std::isdigit(c); }) == s.end();
}

foo() {
    char input[100];
    cin.getline(input, sizeof(input));
    stringstream stream(input);
    while (stream.rdbuf()->in_avail() != 0) {
        std::string n;
        stream >> n;
        if(is_number(n)) {
            numbers.push_back(std::stoi(n));
        }
        else {
            std::cout << "Not valid input. Provide number" << std::endl;
        }
    }
}

int main()
{
    foo();
    return 0;
}

Upvotes: 1

Related Questions