C 程序计算卡在嵌套 while 循环中的文本中的 n 个字母单词的数量

C program to count number of n-letter words in a text stuck in nested while loop

我在离开学校几年后重新开始编码,我一直在尝试用 C 编写一个程序来计算文本中有多少个 n 字母的单词,并将它们存储到一个长度中n 数组,然后打印它们。为简单起见,我假设 n 是 b/w 1 和 10,并且每个单词正好由一个 space 分隔。

这是代码,但是,我的程序似乎永远不会跳出内部 while 循环,因此屏幕上不会打印任何内容。我尝试在该循环的末尾打印一些东西来测试它,由于某种原因程序打印它的次数与字符的数量一样多(包括 spaces,内部 while 条件应该捕获并退出)。我在这里忽略了什么吗?

main()
{
int c, i, j, counter;
counter = 0;
int wlength [10];
for (i=0; i<10; ++i) //initialize array
    wlength[i]=0;
while((c=getchar())!=EOF){ // keep taking input until end of file
    while (c!=' '){   //keep counting until you reach the end of the word
        ++counter;
        c=getchar(); 
    }
    wlength [counter-1]++;  //increment the counter for that word length
    counter=0 ; //reset the counter for the next word
}
for (j=0;j<10;++j) //print the array
    printf("%d ", wlength[j]);

您有两个循环读取标准输入,只有一个检查 EOF。因此,如果在文件末尾之前没有 exactly a space,那么您的程序会读取文件并卡住。 你最好只使用一个循环,用 if - else 语句替换另一个循环:

Pseudo-code :
while ( getchar  and !EOF )
{
    if ( char isn't a space )
    {
        increment counter
    } else {
        increment value for given length
        set first counter to 0
    }
}

您还应该检查您是否在数组的边界内...存在像“expotentially”这样的词 ;-)

问题是inner while loop。因为在 unix 或类 unix 系统中。每行的末尾是 \n。所以你的代码在第一个内循环中被阻塞了。您需要对此进行更多检查。测试条件应更改为:

while(c != ' ' && c != '\n'){
    ++counter;
    c=getchar();
}

我 运行 成功了。