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