0

For example I have the code:

#include <iostream>
using namespace std;

int main()
{
    int test = 0;
    cout << "Please input a number:";

    while(!(cin >> test))
    {
        cout << "Invalid input";
    }

    if(test  == 1)
    {
        cout << "Test is 1";
    }
    else
    {
        // Do something
    }
   return 0;
}

If I input 1abc to the test variable it still continues to process the if statement even though the input is wrong. How could I ignore all the input made and just accept pure numbers in it?

Bhavesh
  • 882
  • 2
  • 9
  • 18
CodingisFun
  • 3
  • 1
  • 4
  • The input is not wrong: it is a number followed by some other characters. – zdf Mar 12 '16 at 05:38
  • [This](http://stackoverflow.com/questions/4654636/how-to-determine-if-a-string-is-a-number-with-c) should help. Read the input as a string (with `std::getline`) and then test if that is a number or not. – Weak to Enuma Elish Mar 12 '16 at 05:42
  • [How to check if the input is a valid integer without any other chars?](https://stackoverflow.com/q/20287186/608639) – jww Jun 28 '18 at 04:07

1 Answers1

2

You can use getline, find_if_not, and isdigit to check if an entire line is a valid integer or not. This will loop until it reads an integer:

std::string number;
while (std::getline(std::cin, number) && number.end() !=
       std::find_if_not(number.begin(), number.end(), &isdigit))
    std::cout << "gitgud!";

getline will read the input up to the newline, and put it in the string. find_if_not and isdigit will find the first non-digit character. If there are none (meaning it is a valid integer), it will return the end iterator.

Weak to Enuma Elish
  • 4,622
  • 3
  • 24
  • 36