字符数的输出是实际的数字加3。
我不知道为什么?
这是代码:
void main(void)
{
int ch,w=0,c=0;
do
{
ch=getche();
++c;
if(ch==32)
{
++w;
++c;
}
}while(ch!=13);
printf("\nnum of characters is %d",c);
printf("\nnum of words is %d",w);
getch();
}
最佳答案
void main(void)
{
int ch,w=0,c=0,lastch=32;
while((ch = getche()) != 13) //get input and check if it's ENTER key
{
++c;
if(ch == 32 && lastch != ch) //make sure two continuous spaces are not counted as a word as pointed out by paxdiablo
++w;
lastch = ch;
}
if(lastch != 32) //for a word with no space
++w;
printf("\nnum of characters is %d",c);
printf("\nnum of words is %d",w);
getch();
}
您可以考虑使用char而不是int。
关于c - C中的字符计数程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2849716/