How to check std :: string if it is really an integer?

The following code converts std::stringto int, and the problem lies in the fact that it cannot be distinguished from a true integer or just a random string. Is there a systematic method to solve this problem?

#include <cstring>
#include <iostream>
#include <sstream>

int main()
{
    std::string str =  "H";

    int int_value;
    std::istringstream ss(str);
    ss >> int_value;

    std::cout<<int_value<<std::endl;

    return 0;
}

EDIT . This is a solution that I liked, because it is very minimal and elegant! This does not work for negative numbers, but I still needed positive ones.

#include <cstring>
#include <iostream>
#include <sstream>

int main()
{
    std::string str =  "2147483647";

    int int_value;
    std::istringstream ss(str);

    if (ss >> int_value)
        std::cout << "Hooray!" << std::endl;

    std::cout<<int_value<<std::endl;


    str =  "-2147483648";
    std::istringstream negative_ss(str);

    if (ss >> int_value)
        std::cout << "Hooray!" << std::endl;

    std::cout<<int_value<<std::endl;

    return 0;
}
+5
source share
3 answers

The WhozCraig principle is much nicer, and I wanted to expand it using an approach that uses the C ++ FAQ , which looks like this:

#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>

class BadConversion : public std::runtime_error {
public:
  BadConversion(std::string const& s)
    : std::runtime_error(s)
    { }
};



inline int convertToInt(std::string const& s,
                              bool failIfLeftoverChars = true)
{
  std::istringstream i(s);
  int x;
  char c;
  if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
    throw BadConversion("convertToInt(\"" + s + "\")");
  return x;
}


int main()
{
    std::cout << convertToInt( "100" ) << std::endl ;
    std::cout << convertToInt( "-100" ) << std::endl ;
    std::cout << convertToInt( "  -100" ) << std::endl ;
    std::cout << convertToInt( "  -100  ", false ) << std::endl ;

    // The next two will fail
    std::cout << convertToInt( "  -100  ", true ) << std::endl ;
    std::cout << convertToInt( "H" ) << std::endl ;
}

, , .

+5

Boost lexical_cast, , .

int number;
try
{
     number = boost::lexical_cast<int>(str);
}
catch(boost::bad_lexical_cast& e)
{
    std::cout << str << "isn't an integer number" << std::endl;
}

@chris, std::stoi ++ 11. std::invalid_argument, . : std:: stoi

+7
/* isdigit example */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main ()
{
  char str[]="1776ad";
  int year;
  if (isdigit(str[0]))
  {
    year = atoi (str);
    printf ("The year that followed %d was %d.\n",year,year+1);
  }
  return 0;
}
+1

All Articles