在c中计算字符程序

0 c

字符编号的输出是实际编号.加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();
}
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 7

您为空格字符递增c 两次.

你的if陈述应该只是:

if(ch==32)
    ++w;
Run Code Online (Sandbox Code Playgroud)

你还有另一个微妙的错误,因为字符串hellospcspcthere(有两个空格)将在你的代码中注册为三个单词.

这就是如何编写它以避免这些问题.注意使用lastch以避免将空间序列计为多个单词.

int main(void) {
    int ch = ' ', lastch, w = 0, c = 0;

    do {
        lastch = ch;
        ch = getchar();
        ++c;
        if (ch == ' ') {
            if (lastch != ' ') {
                ++w;
            }
        }
    } while (ch != '\n');

    if (lastch != ' ') {
        ++w;
    }

    printf("num of characters is  %d\n",c);
    printf("num of words is  %d\n",w);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)