【发布时间】:2012-12-29 06:57:54
【问题描述】:
我有一个几乎很好的工作程序来计算标准输入中的单词。 what has to be count 是一个程序参数。
问题是我使用空格来查看单词,但我也必须在单词本身内计数。 示例:如果我的输入是 aa aaaa #EOF,并且我想计算 aa,那么结果应该是 4。我的代码结果是 2。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
int word_cnt(const char *s, char *argv[])
{
int cnt = 0;
while(*s != '\0')
{
while(isspace(*s))
++s;
if(*s != '\0')
{
if(strncmp(s, argv[1], strlen(argv[1])) == 0)
++cnt;
while(!isspace(*s) && *s != '\0')
++s;
}
}
return cnt;
}
int main(int argc, char *argv[])
{
char buf[1026] = {'\0'};
char *p="#EOF\n";
int tellen = 0;
if (argc != 2)
{
printf("Kan het programma niet uitvoeren, er is geen programma argument gevonden\n");
exit(0);
}
while((strcmp(buf, p) !=0))
{
fgets (buf, 1025, stdin);
tellen += word_cnt(buf, argv);
}
printf("%d", tellen);
return 0;
}
【问题讨论】:
-
什么?你有两个词:
aa和aaaa -
if my input is aa aaaa #EOF, and I want to count aa the result should be 4为什么你的结果应该是 4? -
因为aaaa这个词其实有3次aa,第一个是aa aa,第二个是aaaa,第三个是aaaa.
-
这是我见过的最奇怪的word概念。
-
您的代码将除空格之外的任何内容定义为单词字符。我们通常不会将逗号或引号字符视为单词字符。但我认为这对你的问题并不重要。