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

djaszak
  • 129
  • 8
  • I think you need to iterate the string `input` to check if it is composed only of integer digits before reading it into `n` – Mukul Gupta Jun 05 '16 at 17:10
  • Possible duplicate of http://stackoverflow.com/questions/4654636/how-to-determine-if-a-string-is-a-number-with-c – Mukul Gupta Jun 05 '16 at 17:13
  • 1
    Possible duplicate of [integer input validation, how?](http://stackoverflow.com/questions/13212043/integer-input-validation-how), [Good input validation loop using cin - C++](http://stackoverflow.com/questions/2075898/good-input-validation-loop-using-cin-c) – GingerPlusPlus Jun 05 '16 at 17:18
  • What should the program do when it receives wrong input? – Pete Becker Jun 05 '16 at 17:23

1 Answers1

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;
}
paweldac
  • 1,048
  • 5
  • 11