c++11 int等与string之间的转换

c++11 <string>

增加了全局函数std::to_string,以及std::stoi/stol/stoll等等函数。

to_string(int val)  //int,float,long等转string
int stoi( const std::string& str, size_t *pos = 0, int base = 10 );
size_t string转到的下标,若全部可以转成int,则等于str的大小。
base 就是进制。

stoi

// stoi example
#include <iostream>   // std::cout
#include <string>     // 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

以前是用的<sstream>,封装成如下,还是好用,但是,会每次转换都会生成一个stream对象。会影响性能。应该调用stream.str("");stream.clear();清空,接着转换。

template<class out_type, class in_value>
out_type convert(const in_value & t)
{
    stringstream stream;
    stream << t;//向流中传值
    out_type result;//这里存储转换结果
    stream >> result;//向result中写入值
    return result;
}