int与string类型转化(C++)

int转为string

  1. 利用sstream类
cpp 复制代码
#include <iostream>
#include <sstream>
using namespace std;

int main(){
    int n = 10;
    stringstream ss;
    string str;
    ss << n;
    ss >> str;
    cout << str << endl;
}
  1. sprintf
cpp 复制代码
#include <iostream>
#include <string>
using namespace std;

int main(){
    int n = 10;
    char t[15];
    sprintf(t, "%d", n);  // 转成char类型
    cout << t << endl;
    string str(t);  //转成string类型
    cout << str << endl;

}
  1. to_string
    c++的版本的是C++11
cpp 复制代码
#include <iostream>
#include <string>
using namespace std;

int main(){
    int m = 10;
    string str;
    str = to_string(m);
    cout << str <<endl;
}
相关推荐
阿蒙Amon几秒前
C#常用类库-详解Ecng.Collections
开发语言·c#·ar
m0_528174451 分钟前
C++中的策略模式实战
开发语言·c++·算法
计算机安禾3 分钟前
【C语言程序设计】第30篇:指针与字符串
c语言·开发语言·c++·算法·visualstudio·visual studio code·visual studio
信奥胡老师4 分钟前
GESP 2026年3月C++三级(二进制回文串)
开发语言·c++·算法
小年糕是糕手5 分钟前
【35天从0开始备战蓝桥杯 -- 刷题包】
c语言·jvm·数据结构·c++·算法·蓝桥杯
Allen_LVyingbo9 分钟前
GTC2026前瞻(二)Agentic AI 与开源模型篇+(三)Physical AI 与机器人篇
开发语言·人工智能·数学建模·机器人·开源·知识图谱
liuyao_xianhui11 分钟前
动态规划_最长递增子序列_C++
java·开发语言·数据结构·c++·算法·链表·动态规划
旖-旎13 分钟前
二分查找(搜索插入位置)(3)
c++·算法·二分查找·力扣·双指针
咯哦哦哦哦13 分钟前
windows下VSCode配置C++/CMake/Qt/MVSC 开发环境 【电脑已经安装vs2022】
c++·vscode·qt
程序员爱酸奶14 分钟前
Java常用设计模式
java·开发语言·设计模式