Search code examples
c++stringint

How to use a stoi, and return false if the string has a letter in c++?


So, I have this code in C++, and need to use stoi to test if the String (a) has a letter, if doesn't have, send the number to int, and if has return false.

my code

void main(){

  string a = "a1321";
  int b;
  if (stoi(a)){
    b = stoi(a);
    cout << b << endl;
  }
  else cout << "ERROR"<< endl;

  system("pause");

}

Can anyone help ?


Solution

  • Since stoi returns the integer value if parsed you can't directly use the return value to check for correctness.

    You could catch std::invalid_argument exception but it could be too much. If you don't mind using strol C function instead that std::stoi you can do something like

    bool isNumber(const std::string& str)
    {
      char* ptr;
      strtol(str.c_str(), &ptr, 10);
      return *ptr == '\0';
    }
    

    which exploits the fact that the function sets the second char** argument to the first non numerical character in the passed string, which should be '\0' for a string which just contains a number.