c - 打印字长数组未按预期工作

标签 c arrays

<分区>

我的代码没有按预期工作。我创建了一个数组来跟踪字长。对于输入“test test test”,我想输出数组:[0 0 0 3 0 0 0 0 0 0]。

我的实际输出是:[0 0 0 0 2 0 0 0 0 0]

这是我的代码:

#include <stdio.h>

main()
{
int c, i, characters;
int word_lengths [10];

characters = 0; //word character count

for (i = 0; i <10; ++i)
    word_lengths[i] = 0;  //initialize histogram

while ((c = getchar()) != EOF)
{
    if (c == ' ' || c == '\t' || c == '\n'){   //if blank/tab/new line, reset the character count for new word
        if (characters != 0){     //end of word, increment word length count
            ++word_lengths[characters-1];   //array index starts at 0
        }
        characters = 0;
    }
    else {  //inside a word: increment character count
        ++characters;
    }

}
++word_lengths[characters-1];

for (i = 0; i <10; ++i)
    printf("Length of words = %d\n", word_lengths[i]);
}

我做错了什么?

最佳答案

您确定没有忘记编译您的更改吗?也许您进行了一些代码更改,并且碰巧正在查看以前的构建。

关于c - 打印字长数组未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18004470/

相关文章:

c - 汇编的 Linux 系统调用表或速查表

c - 使用 C 中的按位运算符查找值是否在某个范围内

无法从 Matlab Coder 创建 .dll

c# - 了解不安全代码及其用途

c - 使用用户输入元素声明数组

误报概率低的校验和

c++ - 2的平方根,点后需要x位数字

javascript - 用单选按钮排列键

c - 在c中使用char数组实现一个64 block 逻辑磁盘

c++ - 如果大小未知,如何通过引用将一维数组作为参数传递?