Almas
Almas

Reputation: 3

How to work with integer limits in C++. The number "-91283472332" is out of the range of a 32-bit signed integer

**Some problems in code. I must convert a string to an integer. But have limited, 32-bit signed integer. I used the `stoi() function, and did not remember about spaces in string, however using big numbers are impossible. ** My code:

#include <iostream>
#include <string>
#include <limits.h>
using namespace std;

int myAtoi(string str)
{
    int Res = 0;
    for (int i = 0; i < str.size(); i++)
    {
        if (str[0] >= 'a' && str[0] <= 'z')
        {
            return 0;
        }
    }
    for (int i = 0; i < str.size(); i++)
    {
        if (str[i] == ' ')
            i++;
        // if(str[i]>='0' || str[i]<='9' )
        //// if(str[i]==' ')
        ////    i++;
        Res = stoi(str);
        cout << "Res:" << Res << endl;
        if (Res <= INT_MIN)
        {
            return INT_MIN;
        }
        if (Res >= INT_MAX)
        {
            return INT_MAX;
        }
    }
    cout << "MIN=" << INT_MAX << endl;
    cout << "Res=" << Res;
    // return Res;
}

Upvotes: 0

Views: 230

Answers (1)

Rohan Bari
Rohan Bari

Reputation: 7726

Get the help of stoll() which converts a std::string object into long long type integer:

void printLongNumber(std::string str) {
    auto number = stoll(str);
    std::cout << number << std::endl;
}

Upvotes: 2

Related Questions