Reputation: 129
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.
Upvotes: 0
Views: 827
Reputation: 153458
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);
Upvotes: 4