看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《blackcity (超黑城市)》之銘言: : 開發平台(Platform): (Ex: Win10, Linux, ...) : Win10 : 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) : GCC Eclipse : 問題(Question): : 1. string AddPadding(int PadLen, string Str) : { : char buff[100]; : snprintf(buff, 100, " %*s", PadLen, Str.c_str()); : return buff; : } 不曉得你有沒有思考過下面幾種呼叫方式的差別, 以及它們的正確 性: AddPadding( -1, "hello world"); AddPadding(100, "hello world"); const std::string s("hello world"); AddPadding(100, s); : 2. string AddPadding(int PadLen, string Str, char* buff) : { : snprintf(buff, 100, " %*s", PadLen, Str.c_str()); : return buff; : } char c; AddPadding(100, "hello world", &c); AddPadding(100, "hello world", nullptr); : 3. string AddPadding(int PadLen, string Str, char* buff) : { : int PadCount = PadLen - Str.length() + 1; : for (int Index = 0; Index < PadCount; Index++) : { : buff[Index] = ' '; : } : strcpy(buff + PadCount, Str.c_str()); : return buff; : } : Note: (2)(3)外部宣告char buff[100]; : 想請問一下,第一種寫法是可行的嗎? : 還是會有機會造成buff的空間釋放後資料錯誤? : 第二種和第三種寫法應該是結果相同且能保證回傳的資料沒問題吧... : 謝謝 如果只是要將原字串轉換為長度至少為 N 的字串, 前方補特定字元 , 其實用 std::string 本身的成員函式就可以了. 不需要依賴額外 的記憶體空間, 且把大小寫死進而產生呼叫的潛規則: string addPadding( string::size_type n, const string& str, string::value_type c = ' ' ) { string result; // allocate memory only once result.reserve(std::max(str.length(), n)); // append padding chars result.append(str.length() < n ? n - str.length() : 0, c); // append str itself return result.append(str); } 這邊用 const std::string& 來接引數是為了避免不必要的物件拷 貝; 然而如果要進一步避免隱式轉換, 還需要提供參數為 const char* 的多載版本. example: https://bit.ly/2TFAik5 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 180.176.51.8 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1553882432.A.F14.html ※ 編輯: poyenc (180.176.51.8), 03/30/2019 02:06:31
tomnelson: 這篇m起來 03/30 10:05