开发者

counting characters program in c

开发者 https://www.devze.com 2022-12-30 08:01 出处:网络
The output of characters number is the actual no. plus 3. I don\'t know why? This is the code: 开发者_StackOverflow中文版void main(void)

The output of characters number is the actual no. plus 3. I don't know why?

This is the code:

开发者_StackOverflow中文版
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();
}


You're incrementing c twice for the space character.

Your if statement should be just:

if(ch==32)
    ++w;

You have another subtle bug as well inasmuch as the string hellospcspcthere (with two spaces) will register as three words in your code.

This is how I would have written it to avoid those problems. Note the use of lastch to avoid counting space sequences as multiple words.

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;
}


You're double-counting spaces:

++c;
if(ch==32)
{
    ++w;
    ++c;
}

You already incremented c; you don't need to do it again. You're also counting the newline as a character, and your word count is a count of the number of spaces, which is going to be short one ("foo bar" has two words, but one space). Depending on what exactly you want to check, standard functions like isspace might be easier (but it returns true for things besides ' ')


  ++c;
  if(ch==32)
  {
      ++w;
      ++c;
  }

You have double-counted the space character. Remove the 2nd ++c.


Each space is counted twice...

  ++c;
  if(ch==32)
  {
      ++w;
      ++c; // char is counted again
  }

Change code to:

  ++c;
  if(ch==32)
  {
      ++w;     
  }


You are adding to c twice when ch==32. Also, you are adding to c when ch==13.


You're counting spaces twice.

Also it's easier to read if you use character literals like ch==' ' instead of ch==32


You're incrementing c twice, if the character read is 32.


Each space is counted twice


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();
}

You can consider using char instead of int.

0

精彩评论

暂无评论...
验证码 换一张
取 消