溫馨提示×

c++中int轉string的方法是什么

c++
小億
322
2023-10-14 00:23:18
欄目: 編程語言

在C++中,可以使用以下幾種方法將int轉換為string:

  1. 使用std::to_string函數:std::to_string是C++11標準庫中的一個函數,它可以將整數轉換為對應的字符串。示例代碼如下:
int num = 123;
std::string str = std::to_string(num);
  1. 使用std::stringstream類:std::stringstream是C++標準庫中的一個類,它可以將各種類型的數據轉換為字符串。示例代碼如下:
#include <sstream>
int num = 123;
std::stringstream ss;
ss << num;
std::string str = ss.str();
  1. 使用std::sprintf函數:std::sprintf是C標準庫中的一個函數,可以將格式化的文本輸出到一個字符數組中??梢岳眠@個函數將整數轉換為字符串。示例代碼如下:
#include <cstdio>
int num = 123;
char buf[10];
std::sprintf(buf, "%d", num);
std::string str(buf);

以上是三種常用的將int轉換為string的方法,根據實際情況選擇適合的方法即可。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女