How can I convert a std::string to int?

后端 未结 19 1079
梦毁少年i
梦毁少年i 2020-11-22 02:10

Just have a quick question. I\'ve looked around the internet quite a bit and I\'ve found a few solutions but none of them have worked yet. Looking at converting a string to

19条回答
  •  梦毁少年i
    2020-11-22 02:43

    Well, lot of answers, lot of possibilities. What I am missing here is some universal method that converts a string to different C++ integral types (short, int, long, bool, ...). I came up with following solution:

    #include
    #include
    #include
    #include
    
    using namespace std;
    
    template
    T toIntegralType(const string &str) {
        static_assert(is_integral::value, "Integral type required.");
        T ret;
        stringstream ss(str);
        ss >> ret;
        if ( to_string(ret) != str)
            throw invalid_argument("Can't convert " + str);
        return ret;
    }
    

    Here are examples of usage:

    string str = "123";
    int x = toIntegralType(str); // x = 123
    
    str = "123a";
    x = toIntegralType(str); // throws exception, because "123a" is not int
    
    str = "1";
    bool y = toIntegralType(str); // y is true
    str = "0";
    y = toIntegralType(str); // y is false
    str = "00";
    y = toIntegralType(str); // throws exception
    

    Why not just use stringstream output operator to convert a string into an integral type? Here is the answer: Let's say a string contains a value that exceeds the limit for intended integral type. For examle, on Wndows 64 max int is 2147483647. Let's assign to a string a value max int + 1: string str = "2147483648". Now, when converting the string to an int:

    stringstream ss(str);
    int x;
    ss >> x;
    

    x becomes 2147483647, what is definitely an error: string "2147483648" was not supposed to be converted to the int 2147483647. The provided function toIntegralType spots such errors and throws exception.

提交回复
热议问题