Re: [問題]複製字串使用strcpy、strcpy_s 搭配上new

看板C_and_CPP作者時間10年前 (2014/01/03 00:44), 編輯推噓2(202)
留言4則, 4人參與, 最新討論串2/2 (看更多)
※ 引述《bestman8556 (廷廷)》之銘言: : 開發平台(Platform): (Ex: VC++, GCC, Linux, ...) : VC++ 2013 : 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) : 無。 : 問題(Question): : 1.在VC 2010版本,使用strcpy來複製字串,在compiler僅有僅告的提示。 : 但在VC 2013版本,使用strcpy變成錯誤訊息,硬是要我使用strcpy; : 改成strcpy_s使用時發現: : void test(char *text) : char *str1; : str1=new char[strlen(tx)+1]; : strcpy(str1,text); 這行出現錯誤。 : strcpy_s(str1,text);所以依循更改訊息我更換成此行。 : 但卻出現以下錯誤訊息: : IntelliSense: 多載函式 "strcpy_s" 沒有任何執行個體符合引數清單 : 引數類型為: (char *, char *) : 我試著把new取消就不會有這個錯誤訊息跑出。 : 想請問,我硬是要用new的話,有甚麼辦法可以解決呢??? 我查 MSDN http://msdn.microsoft.com/en-us/library/td1esda9.aspx VC 2013 的 strcpy_s 有兩個版本: errno_t strcpy_s( char *strDestination, size_t numberOfElements, const char *strSource ); template <size_t size> errno_t strcpy_s( char (&strDestination)[size], const char *strSource ); // C++ only 所以要用第一個版本的話要加上 numberOfElements 參數: strcpy_s(str1, strlen(text), text) 如果用第二個版本的話,第一個參數就一定要是 char array,不能是 pointer。 : 2.想問,不知道還有甚麼指令,或是辦法可以複製字串呢?? 我會建議用 strncpy,這個是 C 和 C++ 標準就有的,不是 VC 特有的。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.30.49

01/03 00:47, , 1F
strncpy M$ 上面應該還是會噴 warning ... strncpy_s Orz
01/03 00:47, 1F

01/03 00:50, , 2F
哈 那就用 std::copy 吧...
01/03 00:50, 2F

01/03 09:37, , 3F
請愛用 char_traits<T>::copy()
01/03 09:37, 3F

01/03 23:54, , 4F
感謝LOVE大大,以你的方式順利解決!!
01/03 23:54, 4F
文章代碼(AID): #1InPTbfG (C_and_CPP)
文章代碼(AID): #1InPTbfG (C_and_CPP)