これは本当に簡単だと思いましたが、いくつかの困難を伴います。私が持っている場合
std::string name = "John";
int age = 21;
それらを組み合わせて単一の文字列を取得するにはどうすればよい"John21"ですか?
これは本当に簡単だと思いましたが、いくつかの困難を伴います。私が持っている場合
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);
#include <string>)#include <sstream>(標準C ++から)String(number)いる場合は、も使用できます。
                    C ++ 11ではstd::to_string、たとえば次のように使用できます。
auto result = name + std::to_string( age );
              Boostがある場合は、を使用して整数を文字列に変換できますboost::lexical_cast<std::string>(age)。
もう1つの方法は、文字列ストリームを使用することです。
std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;
3番目のアプローチは、Cライブラリを使用するsprintfかsnprintf、Cライブラリから取得することです。
char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;
他のポスターはの使用を提案しましたitoa。これは標準関数ではないため、使用するとコードは移植できなくなります。それをサポートしないコンパイラがあります。
sprintf答えには、は発生しませんsnprintf。
                    #include <iostream>
#include <sstream>
std::ostringstream o;
o << name << age;
std::cout << o.str();
              #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から恥知らずに盗まれました。
s  スタック変数のメモリであり、s呼び出し後に無料になりますitos。sヒープから割り当てるべきでありfree、使用後は正しいですか?
                    C ++ 11を使用してstd::to_stringいる場合は、を使用できます。
例:
std::string name = "John";
int age = 21;
name += std::to_string(age);
std::cout << name;
出力:
John21
              name += std::to_string(age + 0LL);代わりにどうですか?
                    最も簡単な答えはsprintf関数を使用することだと私には思えます:
sprintf(outString,"%s%d",name,age);
              この問題はさまざまな方法で実行できます。2つの方法で示します。
を使用して数値を文字列に変換しますto_string(i)。
文字列ストリームの使用。
コード:
#include <string>
#include <sstream>
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main() {
    string name = "John";
    int age = 21;
    string answer1 = "";
    // Method 1). string s1 = to_string(age).
    string s1=to_string(age); // Know the integer get converted into string
    // where as we know that concatenation can easily be done using '+' in C++
    answer1 = name + s1;
    cout << answer1 << endl;
    // Method 2). Using string streams
    ostringstream s2;
    s2 << age;
    string s3 = s2.str(); // The str() function will convert a number into a string
    string answer2 = "";  // For concatenation of strings.
    answer2 = name + s3;
    cout << answer2 << endl;
    return 0;
}+出力演算子を持つものの連結に使用したい場合は、次のテンプレートバージョンを提供できます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
これは最も効率的な方法ではありませんが、ループ内で多くの連結を行わない限り、最も効率的な方法は必要ありません。
std::stringため、文字列を必要な型に変換できない式では候補になりません。例えば、これがoperator+ために使用の対象ではありません+の中で   int x = 5 + 7;。すべてを考慮して、非常に説得力のある理由なしにこのような演算子を定義することはありませんが、私の目的は、他とは異なる答えを提供することでした。
                    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"
}
              Qtに関連する質問がクローズされたため、Qtを使用してそれを行う方法は次のとおりです。
QString string = QString("Some string %1 with an int somewhere").arg(someIntVariable);
string.append(someOtherIntVariable);
文字列変数には、%1の代わりにsomeIntVariableの値があり、最後にsomeOtherIntVariableの値があります。
整数(または他の数値オブジェクト)を文字列と連結するために使用できるオプションは他にもあります。それは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;
}
              以下は、IOStreamsライブラリの解析およびフォーマットファセットを使用して、intを文字列に追加する方法の実装です。
#include <iostream>
#include <locale>
#include <string>
template <class Facet>
struct erasable_facet : Facet
{
    erasable_facet() : Facet(1) { }
    ~erasable_facet() { }
};
void append_int(std::string& s, int n)
{
    erasable_facet<std::num_put<char,
                                std::back_insert_iterator<std::string>>> facet;
    std::ios str(nullptr);
    facet.put(std::back_inserter(s), str,
                                     str.fill(), static_cast<unsigned long>(n));
}
int main()
{
    std::string str = "ID: ";
    int id = 123;
    append_int(str, id);
    std::cout << str; // ID: 123
}
              #include <sstream> std::ostringstream s; s << "John " << age; std::string query(s.str());
std::string query("John " + std::to_string(age));
#include <boost/lexical_cast.hpp> std::string query("John " + boost::lexical_cast<std::string>(age));
私が書いた関数があり、これはint番号をパラメーターとして取り、それを文字列リテラルに変換します。この関数は、1桁を対応する文字に変換する別の関数に依存しています。
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;
}
              auto result = fmt::format("{}{}", name, age);
ライブラリのサブセットは、標準化のためにP0645 Text Formattingとして提案されており、受け入れられた場合、上記は次のようになります。
auto result = std::format("{}{}", name, age);
免責事項:私は{fmt}ライブラリの作成者です。
Boost::lexical_cast、std::stringstream、std::strstream(非推奨されている)、およびsprintf対snprintf。