解决error: ‘to_string’ was not declared in this scope

to_string是c++11的新方法 可以将数值类型很轻松的转换为字符串类型。

官方的解释如下:

Convert numerical value to string

Returns a with the representation of val.

使用方法如下:

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);

使用to_string时需要引入头文件<string>

to_string在命名空间std中 ,可以直接使用std::to_string(val) 也可以使用前声明using std::to_string或者using namespace std

// to_string example
#include <iostream>   // std::cout
#include <string>     // std::string, std::to_string

int main ()
{
  std::string pi = "pi is " + std::to_string(3.1415926);
  std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
  std::cout << pi << 
;
  std::cout << perfect << 
;
  return 0;
}

然而编译时报错:‘to_string’ is not a member of ‘std’

其实是g++默认不支持c++11标准, 编译时在编译命令上加上 -std=c++11 就好咯~

经验分享 程序员 微信小程序 职场和发展