0

I am writing a code to take an integer ID from the user which is later validated from a file. Now when I don't enter a valid input in the cin it doesn't work (obviously). I have attached a sample code below like this:

std::cout << "Enter ID : " << std::endl;
std::cin >> id;

It's simple as that. Now if I enter an input like a or any other character, I can check for any error using cin.fail() But if I enter an input like 11a that doesn't seem to work. I have searched a lot on the internet but couldn't find any suitable solution.

SumranMS
  • 3
  • 1

1 Answers1

1

Welcome to Stack firstly. Try this

#include <iostream>
#include <string>

int main() {

    std::string theInput;
    int inputAsInt;

    std::getline(std::cin, theInput);

    while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {

        std::cout << "Error" << std::endl;

        if( theInput.find_first_not_of("0123456789") == std::string::npos) {
            std::cin.clear();
            std::cin.ignore(256,'\n');
        }

        std::getline(std::cin, theInput);
    }

    std::string::size_type st;
    inputAsInt = std::stoi(theInput,&st);
    std::cout << inputAsInt << std::endl;
    return 0;
}

I made an output to visualize it. The variable "inputAsInt" would be the one you have to further work with.

secdet
  • 300
  • 1
  • 2
  • 11
  • This is the correct answer (first read as string, then validate, then convert), but of course the definition of what is a valid integer can vary (negative numbers for instance); – john Jan 05 '21 at 13:52
  • he said he wants to read an ID so I assumed the ID's are positive. – secdet Jan 05 '21 at 13:56
  • Of course, just pointing it out for any future readers. I did up vote the answer. – john Jan 05 '21 at 13:57
  • @secdet Thanks man its working great for me. Thanks for the help. – SumranMS Jan 05 '21 at 14:58
  • @SumranMS no problem your are welcome! and by the way: welcome to the forum! – secdet Jan 05 '21 at 19:22