#include <stdlib.h>
#include <stdio.h>
int main()
{
unsigned long c;
unsigned long line;
unsigned long word;
char ch;
c = 0;
line = 0;
word = 0;
while((ch = getchar()) != EOF)
{
c ++;
if (ch == '\n')
{
line ++;
}
if (ch == ' ' || ch == '\n' || ch =='\'')
{
word ++;
}
}
printf( "%lu %lu %lu\n", c, word, line );
return 0;
}
我的程序在大多数情况下工作正常,但是当我添加额外的空格时,它会将空格计为额外的单词。例如,
How are you?被计为10个单词,但我希望它计为3个单词。我怎么能修改我的代码才能使它工作?
答案 0 :(得分:0)
我找到了一种计算单词的方法,在它们之间有几个空格,程序只计算单词而不是几个空格也计算单词 这是代码:
MainApp
是单词数,nbword
是输入的字符,c
是以前输入的字符。
prvc
答案 1 :(得分:-1)
这是一种可能的解决方案:
#include <stdlib.h>
#include <stdio.h>
int main()
{
unsigned long c;
unsigned long line;
unsigned long word;
char ch;
char lastch = -1;
c = 0;
line = 0;
word = 0;
while((ch = getchar()) != EOF)
{
c ++;
if (ch == '\n')
{
line ++;
}
if (ch == ' ' || ch == '\n' || ch =='\'')
{
if (!(lastch == ' ' && ch == ' '))
{
word ++;
}
}
lastch = ch;
}
printf( "%lu %lu %lu\n", c, word, line );
return 0;
}
希望这有所帮助,祝你好运!