C++ -> 字符串庫 -> std::basic_string
定義於頭文件
std::string to_string(int value); (1) (C++11起)
std::string to_string(long value); (2) (C++11起)
std::string to_string(long long value); (3) (C++11起)
std::string to_string(unsigned value); (4) (C++11起)
std::string to_string(unsigned long value); (5) (C++11起)
std::string to_string(unsigned long long value); (6) (C++11起)
std::string to_string(float value); (7) (C++11起)
std::string to_string(double value); (8) (C++11起)
std::string to_string(long double value); (9) (C++11起)
std::to_string是C++標准(2011年)的最新版本中引入的功能。舊的編譯器可能不支持它。
1) 有符號十進制整數轉換為字符串內容相同的std::sprintf(buf, “%d”, value)會產生足夠大的buf.
2) 有符號十進制整數轉換為字符串內容相同的std::sprintf(buf, “%ld”, value)會產生足夠大的buf.
3) 有符號十進制整數轉換為字符串內容相同的std::sprintf(buf, “%lld”, value)會產生足夠大的buf.
4)std::sprintf(buf, “%u”, value)會產生足夠大的buf了同樣內容的一個字符串轉換成一個無符號十進制整數.
5)std::sprintf(buf, “%lu”, value)會產生足夠大的buf了同樣內容的一個字符串轉換成一個無符號十進制整數.
6)std::sprintf(buf, “%llu”, value)會產生足夠大的buf了同樣內容的一個字符串轉換成一個無符號十進制整數.
6)std::sprintf(buf, “%llu”, value)會產生足夠大的buf了同樣內容的一個字符串轉換成一個無符號十進制整數.
7,8) std::sprintf(buf, “%f”, value)會產生足夠大的buf了同樣內容的一個字符串轉換成一個浮點值.
9) std::sprintf(buf, “%Lf”, value)會產生足夠大的buf了同樣內容的一個字符串轉換成一個浮點值.
參數
value - 一個數值轉換
返回值
一個字符串保持轉換后的值
示例
#include <iostream>
#include <string>
int main()
{
double f = 23.43;
std::string f_str = std::to_string(f);
std::cout << f_str << '\n';
}
輸出:
23.430000
另請參閱
to_wstring(C ++11)
將整數或浮點值轉換為wstring (函數)
在較低版本C++標准中有另外幾種格式將整數轉為字符串:
1.cstdlib中的itoa() (非標准的C函數, Windows特有的);
2.sprintf();
3.stringstream.str();
相關鏈接:
http://www.cplusplus.com/reference/string/to_string/
https://stackoverflow.com/questions/662976/how-do-i-convert-from-stringstream-to-string-in-c
https://stackoverflow.com/questions/1374468/stringstream-string-and-char-conversion-confusion