本文作者: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::thread - 线程管理join/detach 阅读2239次,点赞0次
- C++ - const修饰符与指针 阅读261次,点赞1次
- C++ - 使用ffmpeg读取视频旋转角度并使用OpenCV根据旋转角度对视频进行旋转复原 阅读1697次,点赞0次
- C++ – 字节数组byte[]或者unsigned char[]与bool的相互转换 阅读858次,点赞1次
- C++ - std::map - 存储动态指针时正确释放内存 阅读4039次,点赞1次
- C++ - 常用的C++命令行参数解析第三方库 阅读2301次,点赞2次
- Centos7 编译C++项目错误解决 : terminate called after throwing an instance of 'std::regex_error' 阅读2428次,点赞1次
- C++ - RAII机制 阅读237次,点赞0次
- C++ - std::map正向遍历与反向遍历的几种方式 阅读4132次,点赞3次
- 计算几何 - C++计算两个二维向量的夹角 阅读3827次,点赞3次
全站随机文章推荐
- 资源分享 - Jim Blinn's Corner - A Trip Down the Graphics Pipeline 英文高清PDF下载 阅读2708次,点赞3次
- 书籍翻译 – Fundamentals of Computer Graphics, Fourth Edition,第6章 Transformation Matrices中文翻译 阅读1517次,点赞7次
- Centos7 - 配置Go环境 阅读2702次,点赞1次
- 资源分享 - 计算机图形学 第2版,Fundamentals of Computer Graphics(Second Edition) 中文版PDF下载 阅读3345次,点赞0次
- Python - 使用Python+websockets时报错:AttributeError: module 'websockets' has no attribute 'serve' 阅读1498次,点赞0次
- Python - 列表list遍历方法总结 阅读412次,点赞0次
- Python - 普通函数/lambda匿名函数/类成员函数作为回调函数的用法 阅读1922次,点赞0次
- 资源分享 - Character Animation With Direct3D 英文高清PDF下载 阅读1756次,点赞1次
- 工具API推荐 - 通过QQ号获取QQ头像 阅读1181次,点赞0次
- C++ - 智能指针的正确使用方式 阅读464次,点赞0次
VideoTo3dPoseAndBvh这个项目可以发b站吗
可以啊