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

后端 未结 19 1453
梦毁少年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

    From http://www.cplusplus.com/reference/string/stoi/

    // stoi example
    #include    // std::cout
    #include      // std::string, std::stoi
    
    int main ()
    {
      std::string str_dec = "2001, A Space Odyssey";
      std::string str_hex = "40c3";
      std::string str_bin = "-10010110001";
      std::string str_auto = "0x7f";
    
      std::string::size_type sz;   // alias of size_t
    
      int i_dec = std::stoi (str_dec,&sz);
      int i_hex = std::stoi (str_hex,nullptr,16);
      int i_bin = std::stoi (str_bin,nullptr,2);
      int i_auto = std::stoi (str_auto,nullptr,0);
    
      std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
      std::cout << str_hex << ": " << i_hex << '\n';
      std::cout << str_bin << ": " << i_bin << '\n';
      std::cout << str_auto << ": " << i_auto << '\n';
    
      return 0;
    }
    

    Output:

    2001, A Space Odyssey: 2001 and [, A Space Odyssey]

    40c3: 16579

    -10010110001: -1201

    0x7f: 127

提交回复
热议问题