-4

I am writing in C++ and I have a string. I want to check if this string is only numbers and If it is I want to change the type to long int.

                       stringT = "12836564128606764591"; 
                       bool temp = false;
                       for(char& ch : stringT) 
                       {
                        if(!isdigit(ch)) 
                          { 
                            temp=true;
                            break;
                          }
                       }
                       if(temp != true)
                       {
                        itm = new Item_int((long long) strtoll(stringT.c_str(), NULL, 0));
                        std::cout << " itm:" << *itm << std::endl;


                       }  

but the result of print is: 9223372036854775807

Christ
  • 3
  • 5

2 Answers2

0

First iterate over a string to find any non-numeric characters

bool is_number(const std::string& s)
    {
        std::string::const_iterator it = s.begin();
        while (it != s.end() && std::isdigit(*it)) ++it;
        return !s.empty() && it == s.end();
    }

Than convert string to int if is_number is succesful

long int number = 0;
if (is_number(stringT))
{
  number = std::stol(stringT);
}
P_Andre
  • 730
  • 6
  • 17
0

The number 12836564128606764591 is larger than what can fit into a long long.

The maximum a long long can hold is 9223372036854775807 (assuming long long is 64 bits.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115