数字 => 字符串

1
2
3
4
5
6
7
8
9
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

字符串 => 数字

1
2
3
4
5
6
7
8
int stoi(const string& str, size_t *idx = 0, int base = 10);
long stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);
long long stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);
float stof(const string& str, size_t *idx = 0);
double stod(const string& str, size_t *idx = 0);
long double stold(const string& str, size_t *idx = 0);

结论

  • 优先使用boost::lexical_cast

    • 效率更高

    • 接口统一,代码优雅

    • locale敏感

参考

  1. http://stackoverflow.com/questions/23582089/is-boostlexical-cast-redundant-with-c11-stoi-stof-and-family
  2. http://www.boost.org/doc/libs/1_55_0/doc/html/boost_lexical_cast/performance.html#boost_lexical_cast.performance.tests_description

留言

2015-06-26