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;
}
相关推荐
stevenzqzq17 小时前
Compose基础入门
开发语言·compose
米优17 小时前
C/C++中实现自定义自动释放堆内存空间类
c语言·开发语言·c++
Hncj202217 小时前
项目02--JsonRpc
linux·c++·ubuntu·rpc
傻啦嘿哟17 小时前
Python上下文管理器:优雅处理资源释放的魔法工具
开发语言·python
阿方索17 小时前
Python 基础简介
开发语言·python
Data_agent17 小时前
CNFANS模式淘宝1688代购系统搭建指南
大数据·开发语言·前端·javascript
Sammyyyyy17 小时前
MongoDB 的文档模型与 CRUD 实战
开发语言·数据库·mongodb·servbay
帅那个帅17 小时前
go的雪花算法代码分享
开发语言·后端·golang
挖矿大亨17 小时前
C++中的引用
开发语言·c++