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;
}
相关推荐
L_09072 分钟前
【Algorithm】Day-4
c++·算法·leetcode
煜36433 分钟前
C++异常与智能指针
开发语言·c++
wydaicls37 分钟前
AIDL 接口的定义与生成,使用
java·开发语言
云草桑38 分钟前
C#入坑JAVA 使用XXLJob
java·开发语言·c#
shx666643 分钟前
python杂记
开发语言·python
光头闪亮亮1 小时前
ZBar 环境搭建与快速入门指南
c++
闭着眼睛学算法1 小时前
【双机位A卷】华为OD笔试之【模拟】双机位A-新学校选址【Py/Java/C++/C/JS/Go六种语言】【欧弟算法】全网注释最详细分类最全的华子OD真题题解
java·c语言·javascript·c++·python·算法·华为od
卿摆摆1 小时前
【C++】string的模拟实现
开发语言·c++
Dxy12393102161 小时前
python如何使用nacos
开发语言·网络·python
玫瑰花店2 小时前
C++速通Lambda表达式
开发语言·c++