C++ 将单词从c字符串复制到c字符串的2D数组中

C++ 将单词从c字符串复制到c字符串的2D数组中,c++,computer-science,c-strings,C++,Computer Science,C Strings,所以我需要把一个由字母和空格组成的c字符串转换成一个由c字符串组成的二维数组。二维数组的每一行必须由字母组成,并且只能由字母组成。基本上,我需要把一个句子中的单词组成一个数组 例如:11月日,我的全新bmw lis被盗,我对此感到不安,应将其转换为2d c字符串数组,如:im,不安,即,11月日,我的全新bmw lis被盗。 请注意,th和my之间有两个空格字符&my和brandnew 下面的代码在我的控制台中提供了一些有趣的输出 char document[201] = "im upset t

所以我需要把一个由字母和空格组成的c字符串转换成一个由c字符串组成的二维数组。二维数组的每一行必须由字母组成,并且只能由字母组成。基本上,我需要把一个句子中的单词组成一个数组

例如:11月日,我的全新bmw lis被盗,我对此感到不安,应将其转换为2d c字符串数组,如:im,不安,即,11月日,我的全新bmw lis被盗。 请注意,th和my之间有两个空格字符&my和brandnew

下面的代码在我的控制台中提供了一些有趣的输出

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;
}

复制到2D数组时,请尝试在C字符串的末尾添加一个终止空字符

在C语言中,字符串由以“\0”字符结尾的字符数组表示。您看到的奇怪代码可能是由于未遇到“\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
}
但请确保每次读写操作都不会超过数组维数

您的数组限制为[0..12][0..200]。
请始终检查这一点。=>

k未初始化,文档[k]!='\“0”是未定义的行为。您是对的。k没有显式初始化。我相信它应该默认为0,但可能不可靠,特别是因为输出似乎表明它正在工作。documentArray也必须初始化。这个问题是针对项目的特定部分,因此documentArray[13][201]的初始值设定者是有意的,但非常感谢!编写超出数组维度的内容可能会修改代码、修改变量、跳转到程序中的某个地方;
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
}