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;
}
相关推荐
Tim_104 分钟前
【C++入门】02、C++程序初识
开发语言·c++
lkbhua莱克瓦2412 分钟前
项目知识——Next.js App Router体系
开发语言·javascript·项目知识
Cricyta Sevina18 分钟前
Java 语言多线程核心概念全解析
java·开发语言
小小晓.24 分钟前
Pinely Round 2 (Div. 1 + Div. 2)
c++·算法
缘三水24 分钟前
【C语言】15.指针(5)
c语言·开发语言·指针·语法
爱吃大芒果25 分钟前
从零开始学 Flutter:状态管理入门之 setState 与 Provider
开发语言·javascript·flutter
清风拂山岗 明月照大江33 分钟前
简单文件 IO 示例:使用系统调用读写文件
开发语言·c++·算法
技术净胜34 分钟前
MATLAB文本文件读写实操fopen/fscanf/fprintf/fclose全解析
开发语言·matlab
编织幻境的妖42 分钟前
Python垃圾回收机制详解
开发语言·python