簡體   English   中英

如何在C中輸入的每一行上計算單詞

[英]How to count words on each line of input in C

我試圖制作一個程序,以便它計算每一行的單詞數。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM_LINES 50

int main()
{
char text[NUM_LINES];
int count = 0;
int nw = 0;
char *token;
char *space = " ";
printf("Enter the text:\n");

while (fgets(text, NUM_LINES, stdin)){

    token = strtok(text, space);

    while (token != NULL){

        if (strlen(token) > 0){
            ++nw;
        }
        token = strtok(NULL, space);
    }


    if (strcmp(text , "e") == 0 || strcmp(text , "e\n") == 0){
        break;
    }


}
printf("%d words", nw-1);

return 0;
}

例如,如果輸入是:

Hello my name is John
I would like to have a snack
I like to play tennis
e

我的程序輸出總單詞數(在這種情況下為17)如何計算每一行的單詞數。 因此,在此示例中,我想要的輸出是“ 5 7 5”。

如何分別計算每一行的字數?

只需添加一個本地計數器line_word_count

建議擴展定界符列表以處理最后一個單詞之后的空格。

char *space = " \r\n";

while (fgets(text, NUM_LINES, stdin)){
    int line_word_count = 0;
    token = strtok(text, space);
    while (token != NULL){
        if (strlen(token) > 0){
            line_word_count++;
        }
        token = strtok(NULL, space);
    }
    if (strcmp(text , "e") == 0 || strcmp(text , "e\n") == 0){
        break;
    }
    printf("%d ", line_word_count);
    nw += line_word_count; 
}
printf("\n%d words\n", nw);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM