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;
}
相关推荐
Tony Bai5 小时前
高并发后端:坚守 Go,还是拥抱 Rust?
开发语言·后端·golang·rust
wjs20246 小时前
Swift 类型转换
开发语言
秃了也弱了。6 小时前
python实现定时任务:schedule库、APScheduler库
开发语言·python
weixin_440730506 小时前
java数组整理笔记
java·开发语言·笔记
Thera7776 小时前
状态机(State Machine)详解:原理、优缺点与 C++ 实战示例
开发语言·c++
linux开发之路7 小时前
C++高性能日志库开发实践
c++·c++项目·后端开发·c++新特性·c++校招
niucloud-admin7 小时前
java服务端——controller控制器
java·开发语言
刻BITTER7 小时前
在TRAE 上安装PlatformIO
c++·单片机·嵌入式硬件·arduino
永远都不秃头的程序员(互关)7 小时前
C++动态数组实战:从手写到vector优化
c++·算法
夏幻灵8 小时前
JAVA基础:基本数据类型和引用数据类型
java·开发语言