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;
}
相关推荐
东鹏特饮5 小时前
系统运维(传统/通用运维)面试题
开发语言·php
今天要早睡_6 小时前
C++01_入门基础复习
开发语言·c++
黑马程序员毕设7 小时前
基于 Java 的餐饮点餐系统设计与应用报告
java·开发语言
1-1=08 小时前
C# 委托与事件
开发语言·c#
Fuyo_11198 小时前
C++ 运行时多态与虚函数机制全面剖析【面试重点】
开发语言·c++·面试
w_zero_one9 小时前
递归算法(一)
java·开发语言·算法
Julien200410 小时前
管理机密(一)
运维·服务器·开发语言·学习方法
Chen_harmony10 小时前
七、STL与string类
开发语言·c++
沐晓时光10 小时前
C语言入门,字符串和字符串函数知识讲解
c语言·开发语言
xxxiugou12311 小时前
C++命名空间与引用全解析
开发语言·c++