2013-04-29 50 views
0
int a=sizeof(out); 
int b=sizeof(s2); 
out+=s2; 
out.insert(a,(70-a-b)," "); 

out和s2是字符串。我想在兩個字符串之間添加一些空格字符,並使總長度爲70.VS希望第二個參數爲「const char *」。我讀過C++: insert char to a string,但我仍然不知道如何修改上面給出的代碼。str.insert在VS(C++)中不起作用

感謝您的諮詢!

+0

http://www.cplusplus.com/reference/string/string/insert/ – 2013-04-29 10:00:12

回答

4

out和s2是字符串。我想 之間添加一些空格字符的兩個字符串,使總長度70

首先,sizeof會錯了運營商在這裏。您需要

int a = out.size(); 
int b = s2.size() ; 

一個選擇,做你想要的是

int spaceCount = 70-a-b; 
out += string(spaceCount, ' ') + s2; 

另一種選擇是運輸及工務局局長使用:

ostringstream resultSS; 
resultSS << out << setw(70-out.size()) << right << s2; 
out = resultSS.str(); 
+0

'ostringstream'突然從哪裏來? (其餘的,你必須在將'spaceCount'傳遞給'string'的構造函數之前檢查'spaceCount'是否爲負數。由於有符號到無符號的轉換,負值將不會像人們可以合理預期的那樣表現。) – 2013-04-29 11:09:19

+0

我採取了第一種方法,但似乎spaceCount會在我的代碼中取負值,VS會給出「無效的分配大小:4294967295字節」。所以我添加這一行:int spaceCount = 70-a-b; \t if(spaceCount> 0){spaceCount = spaceCount;} \t else {spaceCount = 1;} – tsinghsia 2013-04-29 12:20:26

+0

@tsinghsia您之前沒有提及您希望至少有1個空白。如果你打算調用'std :: string(spaceCount,'')',你最好使用'std :: max(1,spaceCount)'作爲參數。 (你肯定不需要'if'分支中的'spaceCount = spaceCount;'只需反向測試,然後放下else。) – 2013-04-29 12:45:16

0

參考documentation here

通過這只是糾正最後一個指令:

out.insert(a," ",(70-a-b<70)?(70-a-b):70); 
+0

這實在不夠。如果a是60而b是11,會發生什麼? – 2013-04-29 11:05:52

+0

我改正了,你同意嗎? – 2013-04-29 11:36:39

+0

這是一個聰明的解決方案。但是,爲什麼你不使用'std :: max(70 - (a + b),0)'。 – 2013-04-29 12:42:25

1

雖然它不應該太難插入文本中 問題,一旦你得到正確的大小(使用a.size()b.size()) ,我質疑這是否是最好的解決方案。 我可能會追加out之前 追加s2。喜歡的東西:

int padding = 70 - (asInt(out.size()) + asInt(s2.size())); 
if (padding > 0) { 
    out.append(padding, ' '); 
} 
out.append(s2); 

額外的檢查是必要的,因爲std::string使用的大小 無符號類型(size_t),和無符號類型在C++ 往往會導致一些驚喜的結果。 (該asInt可以或 可能不是必要的,具體情況取決於字串來自 他們基本上是:

int 
asInt(size_t original) 
{ 
    if (original > std::numeric_limits<int>::max()) { 
     throw std::range_error("size too large for int"); 
    return static_cast<int>(original); 
} 

在很多情況下,你就知道該字符串不能太長 才把在計算填充。否則, calculati之前,這點在代碼,所以你不需要 他們。

請注意,您必須大小轉換爲int(或其他一些 簽署型)就會給出錯誤的結果。