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;
}
相关推荐
故事不长丨20 小时前
C#正则表达式完全攻略:从基础到实战的全场景应用指南
开发语言·正则表达式·c#·regex
哈库纳玛塔塔20 小时前
放弃 MyBatis,拥抱新一代 Java 数据访问库
java·开发语言·数据库·mybatis·orm·dbvisitor
你怎么知道我是队长20 小时前
C语言---typedef
c语言·c++·算法
phltxy21 小时前
从零入门JavaScript:基础语法全解析
开发语言·javascript
带土121 小时前
5. enum(枚举)关键字在C/C++中的作用
c语言·c++
天“码”行空21 小时前
java面向对象的三大特性之一多态
java·开发语言·jvm
驴友花雕21 小时前
【花雕学编程】Arduino BLDC 之群体机器人协同探索
c++·单片机·嵌入式硬件·arduino bldc·群体机器人协同探索
驴友花雕21 小时前
【花雕学编程】Arduino BLDC 之仿人机器人膝关节稳定系统
c++·单片机·嵌入式硬件·arduino bldc·仿人机器人膝关节稳定系统
Qhumaing1 天前
C++学习:【PTA】数据结构 7-1 实验7-1(最小生成树-Prim算法)
c++·学习·算法
odoo中国1 天前
Odoo 19 模块结构概述
开发语言·python·module·odoo·核心组件·py文件按