ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

c – 如何连接std :: string和int?

2019-09-11 04:06:40  阅读:244  来源: 互联网

标签:c concatenation int stdstring


我认为这很简单,但它存在一些困难.如果我有

std::string name = "John";
int age = 21;

如何组合它们以获得单个字符串“John21”?

解决方法:

按字母顺序排列:

std::string name = "John";
int age = 21;
std::string result;

// 1. with Boost
result = name + boost::lexical_cast<std::string>(age);

// 2. with C++11
result = name + std::to_string(age);

// 3. with FastFormat.Format
fastformat::fmt(result, "{0}{1}", name, age);

// 4. with FastFormat.Write
fastformat::write(result, name, age);

// 5. with the {fmt} library
result = fmt::format("{}{}", name, age);

// 6. with IOStreams
std::stringstream sstm;
sstm << name << age;
result = sstm.str();

// 7. with itoa
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + itoa(age, numstr, 10);

// 8. with sprintf
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;

// 9. with STLSoft's integer_to_string
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + stlsoft::integer_to_string(numstr, 21, age);

// 10. with STLSoft's winstl::int_to_string()
result = name + winstl::int_to_string(age);

// 11. With Poco NumberFormatter
result = name + Poco::NumberFormatter().format(age);

>是安全的,但很慢;需要Boost(仅限标题);大多数/所有平台
>是安全的,需要C 11(to_string()已包含在#include< string>中)
>安全,快速;要求FastFormat,必须编译;大多数/所有平台
>(同上)
>安全,快速;需要the {fmt} library,可以在仅头模式下编译或使用;大多数/所有平台
>安全,缓慢,冗长;需要#include< sstream> (来自标准C)
>很脆弱(你必须提供足够大的缓冲区),快速,冗长; itoa()是非标准扩展,并不保证可用于所有平台
>很脆弱(你必须提供足够大的缓冲区),快速,冗长;什么都不需要(标准C);所有平台
>很脆弱(你必须提供足够大的缓冲区),probably the fastest-possible conversion,详细;需要STLSoft(仅限标题);大多数/所有平台
> safe-ish(您不会在一个语句中使用多个int_to_string()调用),速度快;需要STLSoft(仅限标题);仅Windows
>是安全的,但很慢;要求Poco C++;大多数/所有平台

标签:c,concatenation,int,stdstring
来源: https://codeday.me/bug/20190911/1803516.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有