Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C程序:需要读取多行输入,直到EOF,并计算字数和行数_C_Count_Eof_Words - Fatal编程技术网

C程序:需要读取多行输入,直到EOF,并计算字数和行数

C程序:需要读取多行输入,直到EOF,并计算字数和行数,c,count,eof,words,C,Count,Eof,Words,我是C语言的新手,这个程序有问题。我试图从标准输入到EOF读取文本,并将读取的字数和输入的行数写入标准输出。定义为除空格以外的任何字符串的词。我的问题是1当程序必须读取一行中的最后一个字时,它读取一行的结尾而不是空格,因此它不会添加该字;2当程序必须读取多行输入时。我是否需要使用FGET执行嵌套for循环才能一直读取!=\N我不确定这一点。以下是我现在拥有的: #include<stdio.h> #include<stdlib.h> #include<string.

我是C语言的新手,这个程序有问题。我试图从标准输入到EOF读取文本,并将读取的字数和输入的行数写入标准输出。定义为除空格以外的任何字符串的词。我的问题是1当程序必须读取一行中的最后一个字时,它读取一行的结尾而不是空格,因此它不会添加该字;2当程序必须读取多行输入时。我是否需要使用FGET执行嵌套for循环才能一直读取!=\N我不确定这一点。以下是我现在拥有的:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>


int main ()
{
    char previousLetter;
    char line[500];
    int numberOfWords, numberOfLines, length, i;

    while (fgets (line, 500, stdin) != NULL)
    {
        length = strlen(line);
        if (length > 0)
        {
            previousLetter = line[0];
        }
        for (i=0; i <= length; i++)
        {
            if(line[i] == ' ' && previousLetter != ' ')
            {
                numberOfWords++;
            }
        previousLetter = line[i];
        }
       numberOfLines++;
   }
   printf ("\n");
   printf ("%d", numberOfWords);
   printf (" %d", (numberOfWords / numberOfLines));
}
fgets存储行尾字符,因此您也可以检查该字符以标记单词的结尾 您的代码已读取多行输入 为什么要使用FGET呢

#include<ctype.h>
#include<stdio.h>

int main(void)
{
        int c;
        enum {in, out} state = out;
        int line_count = 0;
        int word_count = 0;
        while( ( c = fgetc(stdin)) != EOF ) {
                if(isspace(c)) {
                        state = out;
                } else {
                        if( state == out )
                                word_count += 1;
                        state = in;
                }
                if( c == '\n')
                        line_count += 1;
        }
        printf( "words: %d\n", word_count );
        printf( "lines: %d\n", line_count );
        return 0;
}

在单词的开头计数,而不是在单词的结尾计数。另外,numberOfWords和numberOfLines必须初始化为0。不需要FGET。你真正关心的是a是空白吗?如果是的话,b是换行。也应该考虑连续的空格,以避免不正确地填充字数。那么类似这样的事情呢?:ifline[i]=''&&previousLetter!=''||第[i]行='\n'和上一封信(&P)''每次呼叫fgets只会有一个换行符,想想简单的事情这还能用吗?我不确定您的意思是fgets将在换行后再次被调用,还是我的代码将只读取超过一个换行。程序需要能够读取多行,因此需要多行换行。这个代码是否适用于此?对不起,时间不早了,我的脑子不清醒。那就去睡觉吧。当您醒来时读取fgets引用,尤其是其返回值。fgets从流中最多读取一个小于大小的字符,并将它们存储到s指向的缓冲区中。EOF或换行符后,读取停止。如果新行被读取,它将被存储到缓冲区中。缓冲区中最后一个字符后存储了终止的空字节“\0”。所以换行符存储在缓冲区中,所以我应该能够在写的时候比较它,对吗?