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;
}
相关推荐
秦老师Q17 分钟前
php零基础入门到实战,从语法到框架,一篇搞定
开发语言·php
驭渊的小故事1 小时前
多线程02
java·开发语言·jvm
阿里嘎多学长1 小时前
2026-09-09 GitHub 热点项目精选
开发语言·程序员·github·代码托管
fpcc1 小时前
c++编程实践—统一初始化
服务器·c++
君顾11 小时前
本地折扣卡 CPS 平台搭建:从系统架构到落地实战
java·开发语言·折扣卡
liangshanbo12152 小时前
手写 Function.prototype.call 与 Function.prototype.apply 面试题满分答案
开发语言·javascript·原型模式
Zenova EdgeOS2 小时前
C++ 工业边缘 libcurl HTTP 客户端实战
开发语言·c++·网络协议·边缘计算
Jackson_GJH3 小时前
Qt 右键自定义菜单的实现
开发语言·c++·qt
张小姐的猫3 小时前
【AI大模型接入SDK】 —— Gemini接入封装
android·数据结构·数据库·c++·人工智能·python
CoderYanger3 小时前
前端基础——JavaScript(WebAPI)(下篇)
java·开发语言·前端·javascript·程序人生·面试·职场和发展