2015-07-19 125 views
2

嘿,我有一個很長的字符串,我試圖將它固定在一個固定大小的char數組中。我不在乎,如果字符串被砍掉,我只是想要char數組的每個元素有東西。C++如何將大字符串放入固定char數組中

例如

char first_ten_alaphabet[10]; 
string str = "abcdefghijklnopqrstuvwxyz"; 


strcpy(first_ten_alaphabet, str.c_str()); //<-- this will cause program to break 

任何幫助將是不錯的感謝

+2

也許'strncpy()函數(first_ten_alaphabet,10);'?或者,最好添加'first_ten_alphabet [9] ='\ 0';'。 – FoggyDay

+2

@FoggyDay'strncpy'是不安全的,因爲它不能保證目的地是空終止的。 –

回答

3

如果你想複製(也可能截斷)C風格的字符串,那麼我會用strncpy代替「的strcpy() 」。

strncpy()的一個限制是它將而不是如果#/字符完全等於副本長度,則終止該字符串。這是通過設計,但如果你不期望它會成爲潛在的「陷阱」。只需添加這使NULL字符在最後位置上的第二聲明:

char first_ten_alphabet[10]; 
string str = "abcdefghijklnopqrstuvwxyz"; 

strncpy(first_ten_alphabet, str.c_str(), sizeof(first_ten_alphabet)); 
first_ten_alphabet[sizeof(first_ten_alphabet)-1] = '\0'; 
+1

謝謝,這是做的伎倆 – conterio

相關問題