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;
}
相关推荐
傻啦嘿哟43 分钟前
如何在 Python 中使用 colorama 库来给输出添加颜色
开发语言·python
CN-Dust1 小时前
【C++】输入cin例题专题
java·c++·算法
geovindu2 小时前
go: Visitor Pattern
开发语言·设计模式·golang·访问者模式
宣宣猪的小花园.2 小时前
C语言重难点全解析:内存管理到位运算
c语言·开发语言·单片机
方安乐6 小时前
python之向量、向量和、向量点积
开发语言·python·numpy
小小小米粒8 小时前
Collection单列集合、Map(Key - Value)双列集合,多继承实现。
java·开发语言·windows
智者知已应修善业8 小时前
【51单片机中的打飞机设计】2023-8-25
c++·经验分享·笔记·算法·51单片机
czhc11400756638 小时前
C# 428 线程、异步
开发语言·c#
:1219 小时前
java基础
java·开发语言
SilentSamsara9 小时前
Python 环境搭建完整指南:从下载安装到运行第一个程序
开发语言·python