734

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"?

4

24 に答える 24

1271

アルファベット順:

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. 安全ですが遅いです。Boost (ヘッダーのみ)が必要です。ほとんど/すべてのプラットフォーム
  2. 安全で、C++11 が必要です ( to_string()は既に に含まれています#include <string>)
  3. 安全で高速です。コンパイルする必要があるFastFormatが必要です。ほとんど/すべてのプラットフォーム
  4. 同上
  5. 安全で高速です。{fmt} ライブラリが必要です。これは、コンパイルするか、ヘッダーのみのモードで使用できます。ほとんど/すべてのプラットフォーム
  6. 安全で、遅く、冗長です。が必要#include <sstream>です (標準 C++ から)
  7. 壊れやすく (十分な大きさのバッファを提供する必要があります)、高速で冗長です。itoa() は非標準の拡張機能であり、すべてのプラットフォームで使用できるとは限りません
  8. 壊れやすく (十分な大きさのバッファを提供する必要があります)、高速で冗長です。何も必要としません (標準の C++ です)。すべてのプラットフォーム
  9. 脆い (十分な大きさのバッファを提供する必要があります)、おそらく可能な限り最速の変換、冗長です。STLSoft (ヘッダーのみ)が必要です。ほとんど/すべてのプラットフォーム
  10. 安全っぽい (1 つのステートメントで複数のint_to_string()呼び出しを使用しない)、高速。STLSoft (ヘッダーのみ)が必要です。Windows のみ
  11. 安全ですが遅いです。Poco C++が必要です。ほとんど/すべてのプラットフォーム
于 2009-05-22T21:16:32.090 に答える
304

C++11 では、次のように使用できますstd::to_string

auto result = name + std::to_string( age );
于 2012-08-08T08:17:27.660 に答える
91

Boost がある場合は、 を使用して整数を文字列に変換できますboost::lexical_cast<std::string>(age)

もう 1 つの方法は、文字列ストリームを使用することです。

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

3 番目のアプローチは、C ライブラリを使用するsprintfsnprintf、C ライブラリから取得することです。

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

を使用することを提案した他のポスターitoa。これは標準関数ではないため、使用するとコードは移植できなくなります。それをサポートしていないコンパイラがあります。

于 2008-10-10T15:11:04.697 に答える
84
#include <iostream>
#include <sstream>

std::ostringstream o;
o << name << age;
std::cout << o.str();
于 2008-10-10T15:09:47.540 に答える
58
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string itos(int i) // convert int to string
{
    stringstream s;
    s << i;
    return s.str();
}

http://www.research.att.com/~bs/bs_faq2.htmlから恥知らずに盗まれた。

于 2008-10-10T15:09:08.040 に答える
34

これが最も簡単な方法です:

string s = name + std::to_string(age);
于 2014-12-21T21:50:56.137 に答える
18

最も簡単な答えは、sprintf関数を使用することだと私には思えます:

sprintf(outString,"%s%d",name,age);
于 2008-10-10T15:56:48.520 に答える
15
#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
    stringstream s;
    s << name << i;
    return s.str();
}
于 2008-10-10T15:12:52.400 に答える
11
#include <sstream>

template <class T>
inline std::string to_string (const T& t)
{
   std::stringstream ss;
   ss << t;
   return ss.str();
}

次に、使用法は次のようになります

   std::string szName = "John";
   int numAge = 23;
   szName += to_string<int>(numAge);
   cout << szName << endl;

Googled [およびテスト済み:p]

于 2008-10-10T19:53:37.153 に答える
6

+出力演算子を持つものの連結に使用したい場合は、次のテンプレート バージョンを提供できoperator+ます。

template <typename L, typename R> std::string operator+(L left, R right) {
  std::ostringstream os;
  os << left << right;
  return os.str();
}

次に、連結を簡単な方法で記述できます。

std::string foo("the answer is ");
int i = 42;
std::string bar(foo + i);    
std::cout << bar << std::endl;

出力:

the answer is 42

これは最も効率的な方法ではありませんが、ループ内で多くの連結を行う場合を除き、最も効率的な方法は必要ありません。

于 2011-11-03T13:26:07.690 に答える
5

MFC を使用している場合は、CString を使用できます。

CString nameAge = "";
nameAge.Format("%s%d", "John", 21);

Managed C++ には 文字列フォーマッタもあります。

于 2008-10-10T17:13:53.780 に答える
4

std::ostringstream は良い方法ですが、書式設定をワンライナーに変換する次の追加のトリックが便利な場合があります。

#include <sstream>
#define MAKE_STRING(tokens) /****************/ \
    static_cast<std::ostringstream&>(          \
        std::ostringstream().flush() << tokens \
    ).str()                                    \
    /**/

これで、次のように文字列をフォーマットできます。

int main() {
    int i = 123;
    std::string message = MAKE_STRING("i = " << i);
    std::cout << message << std::endl; // prints: "i = 123"
}
于 2008-10-10T22:08:27.583 に答える
4

Qt関連の質問はこれを支持してクローズされたので、Qtを使用してそれを行う方法は次のとおりです。

QString string = QString("Some string %1 with an int somewhere").arg(someIntVariable);
string.append(someOtherIntVariable);

文字列変数は、%1 の代わりに someIntVariable の値を持ち、最後に someOtherIntVariable の値を持ちます。

于 2011-08-10T13:29:46.240 に答える
3

整数 (またはその他の数値オブジェクト) を文字列と連結するために使用できるオプションは他にもあります。Boost.Formatです

#include <boost/format.hpp>
#include <string>
int main()
{
    using boost::format;

    int age = 22;
    std::string str_age = str(format("age is %1%") % age);
}

Boost.Spirit(v2)のKarma

#include <boost/spirit/include/karma.hpp>
#include <iterator>
#include <string>
int main()
{
    using namespace boost::spirit;

    int age = 22;
    std::string str_age("age is ");
    std::back_insert_iterator<std::string> sink(str_age);
    karma::generate(sink, int_, age);

    return 0;
}

Boost.Spirit Karma は、整数から文字列への変換の最速のオプションの 1 つだと主張しています。

于 2010-10-04T10:00:46.697 に答える
3
  • std::ostringstream
#include <sstream>

std::ostringstream s;
s << "John " << age;
std::string query(s.str());
  • std::to_string (C++11)
std::string query("John " + std::to_string(age));
  • ブースト::lexical_cast
#include <boost/lexical_cast.hpp>

std::string query("John " + boost::lexical_cast<std::string>(age));
于 2018-08-03T07:09:47.527 に答える
2

よくある答え: itoa()

これは悪いです。 here でitoa指摘されているように、非標準です。

于 2008-10-10T15:09:04.873 に答える
2

以下の簡単なトリックを使用して int を文字列に連結できますが、これは整数が 1 桁の場合にのみ機能することに注意してください。それ以外の場合は、その文字列に整数を 1 桁ずつ追加します。

string name = "John";
int age = 5;
char temp = 5 + '0';
name = name + temp;
cout << name << endl;

Output:  John5
于 2016-09-28T18:15:44.393 に答える
1

int 数値をパラメーターとして取り、それを文字列リテラルに変換する、私が書いた関数があります。この関数は、1 桁を対応する char に変換する別の関数に依存しています。

char intToChar(int num)
{
    if (num < 10 && num >= 0)
    {
        return num + 48;
        //48 is the number that we add to an integer number to have its character equivalent (see the unsigned ASCII table)
    }
    else
    {
        return '*';
    }
}

string intToString(int num)
{
    int digits = 0, process, single;
    string numString;
    process = num;

    // The following process the number of digits in num
    while (process != 0)
    {
        single  = process % 10; // 'single' now holds the rightmost portion of the int
        process = (process - single)/10;
        // Take out the rightmost number of the int (it's a zero in this portion of the int), then divide it by 10
        // The above combination eliminates the rightmost portion of the int
        digits ++;
    }

    process = num;

    // Fill the numString with '*' times digits
    for (int i = 0; i < digits; i++)
    {
        numString += '*';
    }


    for (int i = digits-1; i >= 0; i--)
    {
        single = process % 10;
        numString[i] = intToChar ( single);
        process = (process - single) / 10;
    }

    return numString;
}
于 2013-08-28T13:23:43.720 に答える