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

后端 未结 19 1434
梦毁少年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条回答
  •  独厮守ぢ
    2020-11-22 03:10

    One line version: long n = strtol(s.c_str(), NULL, base); .

    (s is the string, and base is an int such as 2, 8, 10, 16.)

    You can refer to this link for more details of strtol.


    The core idea is to use strtol function, which is included in cstdlib.

    Since strtol only handles with char array, we need to convert string to char array. You can refer to this link.

    An example:

    #include 
    #include    // string type
    #include    // bitset type used in the output
    
    int main(){
        s = "1111000001011010";
        long t = strtol(s.c_str(), NULL, 2); // 2 is the base which parse the string
    
        cout << s << endl;
        cout << t << endl;
        cout << hex << t << endl;
        cout << bitset<16> (t) << endl;
    
        return 0;
    }
    

    which will output:

    1111000001011010
    61530
    f05a
    1111000001011010
    

提交回复
热议问题