【问题标题】:Setting 2D Char Array to Null in C, but Still Getting Char values?在 C 中将 2D Char 数组设置为 Null,但仍然获取 Char 值?
【发布时间】:2020-09-15 05:03:26
【问题描述】:

本质上,我正在尝试在 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

如何去除垃圾字符?

【问题讨论】:

  • 当你到达输入字符串的空终止符时,你并没有停下来。

标签: arrays c char


【解决方案1】:

当您到达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;
        }
    }

【讨论】:

    猜你喜欢
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 2016-12-08
    • 2021-12-25
    • 2021-08-08
    • 1970-01-01
    相关资源
    最近更新 更多