How do I use standard tools to verify the input of an integer from the console? I want the program to report an error if something like this is entered:

  • 123.3

  • 1223aaw

  • 123 122

Those. only positive and negative integers are allowed.

I tried it myself:

while (!(cin >> k)) { if (cin.fail()) cout << "error" << endl; cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), '\n'); } 

    1 answer 1

    You can read data, and then send it to a special method that will look for invalid characters in the variable.

    Regular expressions are well suited for searching for invalid characters.

    If there are invalid characters, then return true , and if not, then false , and in the calling code you can already generate an exception via throw .

    I found this solution:

     #include <iostream> using namespace std; int main() { int length; int width; cout << "Enter the length: "; cin >> length; // input the length cout << "Enter the width: "; cin >> width; // input the width cout << "The area is "; cout << length * width; return 0; } 

    In theory, if you cannot convert the string to an int, an error will crash.

    • So of course you can, but is there really no library solution for such a standard thing ??? - dimotim
    • @dimotim, updated. - iluxa1810
    • Something is not visible line something. - αλεχολυτ