简体   繁体   中英

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;
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM