次のようなことをしたいと思います。
bool b = ...
string s = "Value of bool is: " + b ? "f" : "d";
私が見た例はすべて を使用coutしていますが、文字列を出力したくありません。保管するだけです。
どうすればいいのですか?可能であれば、 a に代入する例と a に代入する例を 1 つ挙げてchar *くださいstd::string。
次のようなことをしたいと思います。
bool b = ...
string s = "Value of bool is: " + b ? "f" : "d";
私が見た例はすべて を使用coutしていますが、文字列を出力したくありません。保管するだけです。
どうすればいいのですか?可能であれば、 a に代入する例と a に代入する例を 1 つ挙げてchar *くださいstd::string。
コンパイラが十分に新しい場合は、次のものが必要std::to_stringです。
string s = "Value of bool is: " + std::to_string(b);
これはもちろん、または必要に応じて"1"(for true) または"0"(for false) を文字列に追加します。その理由は、型を取るオーバーロードがないため、コンパイラはそれを整数値に変換します。"f""d"std::to_stringbool
もちろん、最初に文字列を宣言してから値を追加する 2 つのステップで行うことができます。
string s = "Value of bool is: ";
s += b ? "f" : "d";
または、今とほとんど同じように行いますが、明示的に 2 番目を として作成しますstd::string。
string s = "Value of bool is: " + std::string(b ? "f" : "d");
編集:charからポインターを取得する方法std::string
これはstd::string::c_strメソッドで行われます。しかし、Pete Becker が指摘したように、このポインターは文字列オブジェクト内のデータを指すため、このポインターの使用方法に注意する必要があります。オブジェクトが破棄されるとデータも破棄され、ポインターが保存されると無効になります。
std::ostringstream s;
s << "Value of bool is: " << b;
std::string str(s.str());
また、表現の代わりにstd::boolalphaor"true"を使用できます。"false"int
s << std::boolalpha << "Value of bool is: " << b;
投稿されたコードはほぼ正しいことに注意してください ( +2 つにすることはできませんchar[])。
std::string s = std::string("Value of bool is: ") + (b ? "t" : "f");
に割り当てるには、char[]次を使用できますsnprintf()。
char buf[1024];
std::snprintf(buf, 1024, "Value of bool is: %c", b ? 't' : 'f');
または単にstd::string::c_str()。
簡単です:
std::string s = std::string("Value of bool is: ") + (b ? "f" : "d");
カプセル化:
std::string toString(const bool value)
{
return value ? "true" : "false";
}
それで:
std::string text = "Value of bool is: " + toString(b);
次の 2 つの手順で操作を実行します。
bool b = ...
string s = "Value of bool is: ";
s+= b ? "f" : "d";
そうしないとconst char *、許可されていない two を合計しようとするため、これが必要です。+=このように、代わりに、演算子 forstd::stringと C 文字列のオーバーロードに依存します。
シンプルに:
bool b = ...
string s = "Value of bool is: ";
if (b)
s += "f";
else
s += "d";
私は使用しますstd::stringstream:
std::stringstream ss;
ss << s << (b ? "f" : "d");
std::string resulting_string = ss.str();
strcat() も使用できます
char s[80];
strcpy(s, "Value of bool is ");
strcat(s, b?"f":"d");
この単純な使用例では、1 つの文字列を別の文字列に追加するだけです。
std::string text = std::string("Value of bool is: ").append( value? "true" : "false" );
ここで、より一般的なソリューションとして、文字列ビルダー クラスを作成できます。
class make_string {
std::ostringstream st;
template <typename T>
make_string& operator()( T const & v ) {
st << v;
}
operator std::string() {
return st.str();
}
};
これはマニピュレータをサポートするように簡単に拡張できます (いくつかの余分なオーバーロードを追加します) が、ほとんどの基本的な用途にはこれで十分です。次に、次のように使用します。
std::string msg = make_string() << "Value of bool is " << (value?"true":"false");
(繰り返しますが、この特定のケースではやり過ぎですが、より複雑な文字列を作成したい場合はこれが役立ちます)。