2012-03-22 148 views
0

我遇到比較2個字符字符串都是同樣的問題時:函數strncpy字符的字符串問題增加長度

char string[50]; 

strncpy(string, "StringToCompare", 49); 

if(!strcmp("StringToCompare", string)) 
//do stuff 
else 
//the code runs into here even tho both strings are the same...this is what the problem is. 

如果我使用:

strcpy(string, "StringToCompare");

,而不是:

strncpy(string, "StringToCompare", 49);

它解決了這個問題,但我寧願插入字符串的長度而不是它自己。

什麼錯嗎?我該如何解決這個問題?

+2

錯的是你使用的是C字符串,而不是的std :: string – 2012-03-22 19:49:06

+0

你必須添加字符串'\ 0'的結尾,因爲您將「string」聲明爲字符的向量,而不是字符串。 – Cristy 2012-03-22 19:49:18

+1

「真實世界」中的字符串是否有49個字符長? – 2012-03-22 19:53:34

回答

2

你忘了把一個終止的NUL字符放到string,所以也許strcmp運行結束。使用此行代碼:

string[49] = '\0'; 

解決您的問題。

+0

這可能是他真實的例子中的問題,但不是在他發佈的測試用例中。在Linux手冊頁中:「如果src'的長度小於'n','strncpy()'用空字節填充'dest'的剩餘部分。」 – 2012-03-22 20:13:25

0

您需要手動設置空終止使用strncpy時:

strncpy(string, "StringToCompare", 48); 
string[49] = 0; 
+0

只有當字符串太長。 – 2012-03-22 19:59:55

+0

@ KarolyHorvath:nem,mindig。 Én是pont ugyaneztírtam。 – 2012-03-22 20:06:26

-1

strcopystrncpy:在這種情況下,他們的行爲相同!

所以你沒有告訴我們真相或整個畫面(如:字符串是至少49個字符長)

0

在許多其他的答案明顯猜測,但快速的建議。

首先,編寫的代碼應該可以工作(事實上,在Visual Studio 2010中工作)。關鍵在於'strncpy'的細節 - 除非源長度小於目標長度(在這種情況下),否則它不會隱含添加終止字符的null。另一方面,strcpy在所有情況下確實包含終止符null,這表明您的編譯器沒有正確處理strncpy函數。

所以,如果這不是你的編譯器的工作,你應該會初始化臨時緩衝區這樣的:

char string[50] = {0}; // initializes all the characters to 0 

// below should be 50, as that is the number of 
// characters available in the string (not 49). 
strncpy(string, "StringToCompare", 50); 

不過,我懷疑這很可能只是一個例子,在現實世界中你源字符串是49(同樣,在這種情況下,您應該傳遞50到strncpy)或更長的字符,在這種情況下,NULL終止符不會被複制到您的臨時字符串中。

我會在回覆評論中的建議以使用std::string(如果有的話)。它爲您處理所有這些問題,因此您可以專注於您的實施,而不是這些陳舊的細節。

0

strncpy中的字節計數參數告訴函數要複製的字節數,而不是字符緩衝區的長度。

所以在你的情況下,你要求從你的常量字符串中複製49個字節到緩衝區,我認爲這不是你的意圖!

但是,這並不能解釋爲什麼你會得到異常結果。你使用什麼編譯器?當我在VS2005下運行這段代碼時,我得到了正確的行爲。

注意strncpy(),取而代之的strncpy_s被棄用,這確實想傳遞給它的緩衝區長度:

strncpy_s (string,sizeof(string),"StringToCompare",49) 
+0

檢查[strncpy](http://msdn.microsoft.com/en-us/library/xdsywd25(v = vs80).aspx)的文檔...'如果count大於strSource的長度,目標字符串填充空字符直到長度count.' ...也就是說它不會複製到「StringToCompare」超出sizeof(「StringToCompare」)... +1以強調'strncpy_s' – user1055604 2012-03-23 15:46:01