文字列を初期化した後、charとchar*を同じ行に追加できますか?
char mod;//this comes in as a parameter
string line = "text";
line += mod;
line += "more text";
それを行うためのより効率的および/またはおそらく1行の方法はありますか?何かのようなもの
string line = "text" + mod + "more text";
文字列を初期化した後、charとchar*を同じ行に追加できますか?
char mod;//this comes in as a parameter
string line = "text";
line += mod;
line += "more text";
それを行うためのより効率的および/またはおそらく1行の方法はありますか?何かのようなもの
string line = "text" + mod + "more text";
s は文字列ではないため、ワンライナーは機能しません。したがって、それらをsと連結するためにchar *
使用することはできません。ポインターを追加するだけです。ワンライナーが必要な場合は、使用できます+
char
string line = string("text") + mod + "more text";
しかし、それはあなたの3行よりも効率的ではありません.
最初のスニペットは実行できますが (コンパイルするだけでわかるはずです!)、2 番目のスニペットは実行できません。
次の使用を検討することもできますstd::stringstream
。
std::stringstream ss;
ss << "text" << mod << "more text";
演算子+=
は非定数参照を返すため、スタックでき+=
ます。それは少し厄介で珍しいもので、次のようになります。
string line = "text";
(line += mod) += "more text";
+
の最初のオペランドが aであることを確認するだけですstd::string
:
string line = string("text") + mod + "more text";
次に、の結果string("text") + mod
は astd::string
であり、それに"more text"
追加することもできます。