如何连接 std: : string 和 int?

I thought this would be really simple but it's presenting some difficulties. If I have

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

How do I combine them to get a single string "John21"?

转载于:https://stackoverflow.com/questions/191757/how-to-concatenate-a-stdstring-and-an-int

csdnceshi61
derek5. Let me add to this: I tried 'str = "hi"; str += 5; cout << str;' and saw no effect. Turns out this calls operator+=(char) and adds a non-printable character.
接近 6 年之前 回复

29个回答

In alphabetical order:

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);
  1. is safe, but slow; requires Boost (header-only); most/all platforms
  2. is safe, requires C++11 (to_string() is already included in #include <string>)
  3. is safe, and fast; requires FastFormat, which must be compiled; most/all platforms
  4. is safe, and fast; requires FastFormat, which must be compiled; most/all platforms
  5. is safe, and fast; requires the {fmt} library, which can either be compiled or used in a header-only mode; most/all platforms
  6. safe, slow, and verbose; requires #include <sstream> (from standard C++)
  7. is brittle (you must supply a large enough buffer), fast, and verbose; itoa() is a non-standard extension, and not guaranteed to be available for all platforms
  8. is brittle (you must supply a large enough buffer), fast, and verbose; requires nothing (is standard C++); all platforms
  9. is brittle (you must supply a large enough buffer), probably the fastest-possible conversion, verbose; requires STLSoft (header-only); most/all platforms
  10. safe-ish (you don't use more than one int_to_string() call in a single statement), fast; requires STLSoft (header-only); Windows-only
  11. is safe, but slow; requires Poco C++ ; most/all platforms
weixin_41568196
撒拉嘿哟木头 That's nearly your entire reputation from a single answer!! You lucky bean ;) I think 8 is standard C (of course also C++), but is probably worth differentiating.
接近 2 年之前 回复
csdnceshi68
local-host See tinyurl.com/234rq9u for a comparison of some of the solutions
接近 10 年之前 回复
csdnceshi54
hurriedly% Apart from the one link you've gfiven, what are you basing your performance comments on?
大约 11 年之前 回复

In C++11, you can use std::to_string, e.g.:

auto result = name + std::to_string( age );

If you have Boost, you can convert the integer to a string using boost::lexical_cast<std::string>(age).

Another way is to use stringstreams:

std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;

A third approach would be to use sprintf or snprintf from the C library.

char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;

Other posters suggested using itoa. This is NOT a standard function, so your code will not be portable if you use it. There are compilers that don't support it.

csdnceshi59
ℙℕℤℝ I see no occurence of sprintf in the answer, only snprintf.
大约 7 年之前 回复
csdnceshi59
ℙℕℤℝ an update on snprintf: it is included in C++11.
大约 7 年之前 回复
csdnceshi80
胖鸭 note that snprintf is equally non-standard c++ (like itoa which you mention). it's taken from c99
11 年多之前 回复
csdnceshi73
喵-见缝插针 My tendency would be to never use sprintf, since this can result in buffer-overflows. The example above is a good example where using sprintf would be unsafe if the name was very long.
接近 12 年之前 回复
csdnceshi68
local-host Note that snprintf is not guaranteed to null-terminate the string. Here's one way to make sure it works: <pre> char buffer[128]; buffer[sizeof(buffer)-1] = '\0'; snprintf(buffer, sizeof(buffer)-1, "%s%d", name.c_str(), age); std::cout << buffer << std::endl; </pre>
接近 12 年之前 回复
std::ostringstream o;
o << name << age;
std::cout << o.str();
weixin_41568126
乱世@小熊 this is great, BYT header file is sstream
3 年多之前 回复
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string itos(int i) // convert int to string
{
    stringstream s;
    s << i;
    return s.str();
}

Shamelessly stolen from http://www.research.att.com/~bs/bs_faq2.html.

weixin_41568126
乱世@小熊 return by value is ok even though the string object has gone out of scope, stackoverflow.com/a/3977119/5393174
接近 2 年之前 回复
weixin_41568126
乱世@小熊 but s is a stack variables, the memory of s will be free after invoke itos. s should allocate from heap, and free after using, right?
接近 2 年之前 回复
weixin_41568127
?yb? thanks for the code, link is broken now :D
3 年多之前 回复

This is the easiest way:

string s = name + std::to_string(age);
csdnceshi67
bug^君 This is a post-C++11 solution!
大约 5 年之前 回复

It seems to me that the simplest answer is to use the sprintf function:

sprintf(outString,"%s%d",name,age);
csdnceshi72
谁还没个明天 sprintf(char*, const char*, ...) will fail on some versions of compilers when you pass a std::string to %s. Not all, though (it's undefined behavior) and it may depend on string length (SSO). Please use .c_str()
接近 12 年之前 回复
csdnceshi61
derek5. snprintf can be tricky (mainly because it can potentially not include the null character in certain situations), but I prefer that to avoid sprintf buffer overflows potential problems.
接近 12 年之前 回复

If you have C++11, you can use std::to_string.

Example:

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

name += std::to_string(age);

std::cout << name;

Output:

John21
csdnceshi73
喵-见缝插针 How about name += std::to_string(age + 0LL); instead?
接近 4 年之前 回复
csdnceshi75
衫裤跑路 It would be name += std::to_string(static_cast<long long>(age)); in VC++ 2010 as you can see here
大约 6 年之前 回复
#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
    stringstream s;
    s << name << i;
    return s.str();
}

Herb Sutter has a good article on this subject: "The String Formatters of Manor Farm". He covers Boost::lexical_cast, std::stringstream, std::strstream (which is deprecated), and sprintf vs. snprintf.

共29条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐