首页 > 解决方案 > 在 C 中将 2D Char 数组设置为 Null,但仍然获取 Char 值?

问题描述

本质上,我试图在 C 中创建一个方法,该方法以 char 数组的形式从用户输入一个句子,并在其单独的行上返回每个单词以及句子中的单词总数。例如,如果用户输入“Hi My Name is Fred”。然后,输出应该是单独一行的每个单词,后跟“Total Number of words: 5”。编码似乎很简单,除了一个我根本无法理解的细节。当总字数不是 5(最大值)时,即使我已经将默认值设置为 '\0',我也会得到一堆随机垃圾字符。这是代码:

int splitAndPrintWords(char s[NUM_STRINGS*STRING_LENGTH]) //NUMSTRINGS is 5 while STRING_LENGTH is 50.
{
    char str[NUM_STRINGS][STRING_LENGTH]; //An array for storing the sentence word by word 
                                          //The first word would be in str[0], the second in str[1], etc.
    
    int count = 0;                                               
    for(int k = 0; k < NUM_STRINGS; k++)          // Here I loop through the 2D array of chars to set 
    {                                             // them all to '\0' values, so they aren't printed.
        for(int p = 0; p < STRING_LENGTH; p++)
        {
            str[k][p] = '\0';
        }
    }

    int k = 0;
    int p = 0;
    for(int i = 0; i < NUM_STRINGS*STRING_LENGTH; i++)  //this loop is for putting each word from the  
    {                                                   //sentence into the new 2d array. 
        if(s[i] != ' ')                                 //I use ' ' as the delimiter between words. 
        {
            str[k][p] = s[i];
            p++; 
        }
        else
        {
            k++;
            p = 0;
        }
    }
    count = k+1;
    for(int i = 0; i < NUM_STRINGS; i++)        //lastly I print each word on it's own line, as intended
    {
        printf("%s\n", str[i]);
    }
    

    return count;                             //returns count so the main method can print how many 
}                                             // words are in the sentence. 

输出结果如下:

输入单词(最多 5 个):为什么为什么

ùw%Γd±■ t■a

字数= 1

另一个例子是

输入单词(最多 5 个): 这是三 这是三

t■a

字数= 3

我如何摆脱垃圾字符?

标签: arrayscchar

解决方案


当您到达s. 否则,您会将终止符之后的垃圾字符复制到str.

    for(int i = 0; i < NUM_STRINGS*STRING_LENGTH && s[i] != '\0'; i++)  //this loop is for putting each word from the  
    {                                                   //sentence into the new 2d array. 
        if(s[i] != ' ')                                 //I use ' ' as the delimiter between words. 
        {
            str[k][p] = s[i];
            p++; 
        }
        else
        {
            k++;
            p = 0;
        }
    }

推荐阅读