1

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

4

1 Answer 1

1

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

2 Comments

Thanks. You forgot #include<algorithm>
@djaszak You're welcome. True I didn't write any includes.

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.