我想這樣做如下:在C++中連接字符串和布爾值?
bool b = ...
string s = "Value of bool is: " + b ? "f" : "d";
所有我見過使用cout
的例子,但我不希望打印的字符串;只是存儲它。
我該怎麼做?如果可能的話,我想要一個例子分配給char *
和一個std::string
。
我想這樣做如下:在C++中連接字符串和布爾值?
bool b = ...
string s = "Value of bool is: " + b ? "f" : "d";
所有我見過使用cout
的例子,但我不希望打印的字符串;只是存儲它。
我該怎麼做?如果可能的話,我想要一個例子分配給char *
和一個std::string
。
如果你的編譯器非常新的,它應該有
std::to_string
:
string s = "Value of bool is: " + std::to_string(b);
這當然會追加
"1"
(用於
true
)或
"0"
(爲
false
)到您的字符串,而不是
"f"
或
"d"
你想。原因是沒有
std::to_string
的過載,其類型爲
bool
,因此編譯器將其轉換爲整數值。
當然,你可以做到這一點在兩步,首先聲明字符串然後附加價值:
string s = "Value of bool is: ";
s += b ? "f" : "d";
或做它幾乎就像你現在要做的,但明確創建第二個爲std::string
:
string s = "Value of bool is: " + std::string(b ? "f" : "d");
編輯:如何從一個std::string
char
指針
這是用std::string::c_str
方法完成的。但正如Pete Becker指出的,你必須小心如何使用這個指針,因爲它指向了字符串對象中的數據。如果對象被破壞,數據也會被銷燬,並且指針如果被保存,現在將會失效。
我會用std::stringstream
:
std::stringstream ss;
ss << s << (b ? "f" : "d");
std::string resulting_string = ss.str();
std::ostringstream s;
s << "Value of bool is: " << b;
std::string str(s.str());
,您可以使用std::boolalpha
有"true"
或"false"
而非int
表示:
s << std::boolalpha << "Value of bool is: " << b;
注意張貼的代碼幾乎是正確的(這是不可能的):
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()
。
兩個步驟進行操作:
bool b = ...
string s = "Value of bool is: ";
s+= b ? "f" : "d";
這是必要的,因爲否則你可能會試圖總結2 const char *
,這是不允許的;這樣,相反,您依賴+=
運算符對std::string
和C字符串的過載。
很簡單:
bool b = ...
string s = "Value of bool is: ";
if (b)
s += "f";
else
s += "d";
你可以使用的strcat()以及
char s[80];
strcpy(s, "Value of bool is ");
strcat(s, b?"f":"d");
簡單:
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);
對於這個簡單的例子,一個字符串只是追加其他:
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");
(再次,這是矯枉過正這種特殊情況下,但如果你想譜寫出更加複雜的字符串這將是有益的)。
+1這個問題很容易理解。 – 2012-08-14 13:30:51
分配給char *的怎麼樣?我試圖調用方法簽名中需要它的函數。 – 2012-08-14 13:36:22
@ asdf4lyfe在字符串上調用'c_str()',它會給你一個'const char *' – 2012-08-14 13:38:47