简体   繁体   中英

How to count words on each line of input in C

Im trying to make a program so it counts the words on each line.

#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;
}

For example if the input is:

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

My program outputs the total words (17 in this case) how do I count the words on each line individually. So the output I would want is "5 7 5" in this example.

How do I count the words on each line individually?

Simply add a local counter line_word_count .

Suggest expanding the delimiter list to cope with spaces after the last word.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM