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;
}
相关推荐
a努力。4 小时前
得物Java面试被问:Netty的ByteBuf引用计数和内存释放
java·开发语言·分布式·python·面试·职场和发展
txinyu的博客4 小时前
连接池问题
服务器·网络·c++
zyxzyx494 小时前
大模型本地化部署实战:从服务器性能调优到低成本落地全攻略
服务器·开发语言·php
初願致夕霞4 小时前
实现具备C++11现代特性的STL——list篇(使用shared_ptr智能指针实现,解决了循环引用问题)
c++·list
雾岛听蓝4 小时前
AVL树实现
开发语言·c++
大只鹅4 小时前
Java集合框架-Collection
java·开发语言
小冷coding4 小时前
【Java】基于Java的线上贷款分发业务技术栈设计方案
java·开发语言
星火开发设计4 小时前
循环结构进阶:while 与 do-while 循环的适用场景
java·开发语言·数据结构·学习·知识·循环
苏宸啊4 小时前
C++模版template(泛型编程)初阶
c++
郝学胜-神的一滴4 小时前
Qt自定义TabWidget:实现左侧标签与水平文本布局
开发语言·c++·qt·程序人生