本文主要介绍在C++ 编程语言中,将整型转换为字符串类型的具体方法。
1 使用to_string函数
在 C++11 标准中,可以使用 to_string 函数,将整型转换为字符串类型。
1.1 to_string函数介绍
to_string 函数的用法如下:
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 函数的作用:Returns a string with the representation of val.
1.2 示例程序
使用 to_string 函数将整型转换为字符串类型的示例代码(inttostring.cpp)内容如下:
#include <iostream>#include <string>using namespace std;int main(){int a = 100;string strTest;strTest = to_string(a) + " is a string.";cout << "a is: " << a << endl;cout << "pszTest is: " << strTest << endl;return 0;}
编译上述代码,命令如下:
g++ -o inttostring inttostring.cpp -std=c++11
注意:编译选项中一定要使用“-std=c++11”选项,因为 to_string 函数是在 C++11 标准中引入的。
执行编译生成的 inttostring 程序,运行结果如下:
上面的运行结果表明,通过使用 to_string 函数,成功将 int 类型转换为 string 类型了。