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;
}
相关推荐
汉克老师5 分钟前
GESP2025年12月认证C++八级真题与解析(单选题10-12)
c++·递归··gesp八级·gesp8级
lly20240612 分钟前
jEasyUI 设置排序指南
开发语言
一起努力啊~23 分钟前
算法刷题--长度最小的子数组
开发语言·数据结构·算法·leetcode
还债大湿兄41 分钟前
huggingface.co 下载有些要给权限的模型 小记录
开发语言·前端·javascript
bkspiderx1 小时前
C++中的map容器:键值对的有序管理与高效检索
开发语言·c++·stl·map
Hard but lovely1 小时前
Linux: 线程同步-- 基于条件变量 &&生产消费模型
linux·开发语言·c++
汤姆yu1 小时前
基于python大数据的协同过滤音乐推荐系统
大数据·开发语言·python
爱学习的小道长1 小时前
Python Emoji库的使用教程
开发语言·python
L_09071 小时前
【C++】高阶数据结构 -- 平衡二叉树(AVLTree)
数据结构·c++
今儿敲了吗1 小时前
C++概述
c++·笔记