[英]C Program: Need to Read Multiple Lines of Input Until EOF and Count Words and Number of Lines
我是C语言的新手,我在使用该程序时遇到了麻烦。 我正在尝试从stdin读取文本直到EOF,并将读取的单词数和输入的行数写入标准输出。 一个单词定义为除空格之外的任何字符串。 我的问题是(1)程序必须读取一行中的最后一个单词时,它读取一行的末尾而不是空格,因此它不添加单词;(2)程序必须读取多行中的单词输入。 我是否需要使用fgets进行嵌套的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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.