2014-11-21 72 views
-2

所以我需要將c字符串(字母和空格)轉換爲c字符串的二維數組。 2D陣列的每個「行」必須由字母和字母組成。基本上我需要拿出一個句子的單詞,並把它們排除在外。應該變成2d的C字符串數組,例如:「im」,「upset」,「that」,「on」,「nov 」, 「日」, 「我的」, 「嶄新」, 「寶馬」, 「三里屯」, 「中」, 「偷」。 (注意到有「日」和「我的」 &「我」和「嶄新」之間有兩個空格字符將c字符串中的單詞複製到c字符串的二維數組中

下面的代碼給了我在我的控制檯一些有趣的輸出...

char document[201] = "im upset that on nov th my brandnew bmw lis were stolen"; 

char documentArray[13][201]; 

for (int i, k, j = 0;document[k] != '\0';) 
{ 
    if (isspace(document[k])) 
    { 
     cout << "found a space" << endl; 
     k++; 
     while (isspace(document[k])) 
     { 
      k++; 
     } 
     i++; 
     j = 0; 
    } 
    if (isalpha(document[k])) 
    { 
     documentArray[i][j] = document[k]; 
     k++; 
     j++; 
    } 
} 

for (int i = 0; i < maxWords +1; i++) 
{ 
    cout << documentArray[i] << endl; 
} 

產生的輸出有一些奇怪的東西。我不知道這意味着什麼(如果你能告訴我那會很棒)。你能幫我解決這個問題嗎?

這裏是控制檯輸出:

im\203\377 
upset 
that 
on 
nov 
th 
my\3261 
brandnew 
bmw_\377 
lis 
were 
stolen\301$r\377 
\377 
+2

'k'未初始化,'document [k]!='\ 0''是未定義的行爲。 – AlexD 2014-11-21 01:42:36

+0

你說得對。 k未明確初始化。我相信它應該默認爲0(也許不可靠),特別是因爲輸出似乎表明它正在工作。 – Sam 2014-11-21 01:46:08

+0

documentArray也必須初始化。 – 2014-11-21 01:51:13

回答

0

後與j++;行插入以下

if (j < 201) { 
    documentArray[i][j+1] = '\0'; # terminate the c string 
} else { 
    documentArray[i][j] = '\0'; # cannot terminate the c string, overwrite the last char to terminate the string 
} 

但請確保每一個讀寫操作不會超過陣列的尺寸。

您的數組限制是documentArray [0..12] [0..200]。 請務必檢查。 =>http://en.wikipedia.org/wiki/Buffer_overflow

+0

這個問題是針對某個項目的特定部分的,因此documentArray [13] [201]的初始化程序是有意的,但非常感謝! – 2014-11-21 04:05:07

+0

超出數組維度的書寫可能會修改您的代碼,修改變量,跳轉到程序中的某處。 ;) – 2014-11-21 04:23:48

0

嘗試添加終止空字符到C字符串複製到二維數組時結束。

在C字符串中,由以'\ 0'字符結尾的字符數組表示。您看到的奇怪代碼可能是未遇到'\ 0'的結果以及字符數組末尾的打印運行。

相關問題