[英]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.