本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:C++ – int转string方法总结
原文链接:https://www.stubbornhuang.com/734/
发布于:2020年02月27日 17:16:31
修改于:2020年03月06日 16:46:26

1 std::to_string(最推荐)
可靠、可移植性高
示例代码:
#include <string>
using namespace std;
int main(){
int n=100;
string str=to_string(n);
return 0;
}
2 itoa函数
缺点:只能在windows使用,移植性很差
示例代码:
#include <string>
using namespace std;
int main() {
int n=100;
char ch[10];
_itoa(n, ch, 10); //10表示十进制,vs2017使用_itoa,其他环境可能使用itoa
//下面把char*转成string
string str(ch, ch+strlen(ch));
return 0;
}
3 stringstream字符串流
缺点:慢的要死
示例代码:
#include <sstream>
#include <string>
using namespace std;
int main(){
stringstream ss;
string str;
int n=100;
ss<<n;
ss>>str;
return 0;
}
4 sprintf() - C语言库函数
优点:可以转换各种进制的数。
缺点:需要先分配足够的char数组,无法顾及数组越界问题。
示例代码:
#include <string>
#include <cstring> // strlen(linux)
using namespace std;
int main() {
int n = 100;
char ch[10];
sprintf(ch, "%d", n);
//下面把char*转成string
string str(ch, ch + strlen(ch));
//printf("%sn",str.c_str());
return 0;
}
当前分类随机文章推荐
- C++11 - std::chrono - 使用std::chrono::duration_cast进行时间转换,hours/minutes/seconds/milliseconds/microseconds相互转换,以及自定义duration进行转换 阅读1363次,点赞0次
- C++ – 字节数组byte[]或者unsigned char[]与float的相互转换 阅读391次,点赞0次
- C++ - C++类的特殊成员函数,析构函数,拷贝构造函数,移动构造函数,赋值运算符,移动赋值运算符介绍和基础语法 阅读250次,点赞0次
- C++11 - 封装std::thread,增加子线程启动、暂停、唤起、停止功能 阅读1481次,点赞0次
- C++ – 字节数组byte[]或者unsigned char[]与bool的相互转换 阅读313次,点赞0次
- C++ - 最简单的将文本文件的内容一次性读取到std::string的方法 阅读2779次,点赞2次
- C++ - linux编译C++代码出现error: use of deleted function std::atomic
::atomic(const std::atomic 阅读350次,点赞0次&) - C++ - 使用正则判断字符串是否全是中文 阅读496次,点赞0次
- C++ - 将std::vector中的数值拷贝到数组中 阅读652次,点赞1次
- C++11/std::atomic - 原子变量(不加锁实现线程互斥) 阅读4199次,点赞1次
全站随机文章推荐
- 资源分享 - Video Game Optimization 英文高清PDF下载 阅读674次,点赞0次
- Alphapose - 在Alphapose中使用yolov3-tiny检测器大幅提升检测性能 阅读1707次,点赞0次
- WordPress - PhpStudy本地环境修改固定链接打不开网页404错误 阅读3285次,点赞1次
- C++ - int转string方法总结 阅读4185次,点赞0次
- Visual Studio - 借助远程Linux服务器环境在Visual Studio中编写和远程调试Linux C++程序 阅读352次,点赞0次
- 资源分享 - Graphics Programming Methods 英文高清PDF下载 阅读1178次,点赞0次
- 姿态估计 - COCO-WholeBody数据集骨骼关节keypoint标注对应 阅读1384次,点赞0次
- 资源分享 - High Dynamic Range Imaging- Acquisition, Display, and Image-Based Lighting ( Second Edition )PDF下载 阅读1731次,点赞0次
- 资源分享 - 深度学习与图像识别:原理与实践 (魏溪含 涂铭 张修鹏著) 高清PDF下载 阅读1328次,点赞0次
- 资源分享 - 深度学习 花书 AI圣经(Deep Learning) 中文PDF下载 阅读3137次,点赞1次
VideoTo3dPoseAndBvh这个项目可以发b站吗
可以啊