2014-11-21 67 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'的结果以及字符数组末尾的打印运行。

相关问题