简体   繁体   中英

Counting Number of words and Characters in a Sentence using C

I tried the below program .

INPUT-: i want help Desired OUTPUT-:Words=3 Characters=9

But the actual output deviates from the desired. Can someone tell what is my mistake .

include

void main()
{
  int countch=0;
  int countwd=1;

  printf("Enter your sentence in lowercase: ");
  char ch='a';
  while(ch!='\r')
  {
    ch=getche();
    if(ch==' ')
      countwd++;
    else
      countch++;
  }

  printf("\n Words = ",countwd);

  printf("Characters = ",countch-1);

  getch();

}

Be advised: getchar() returns int , not char . This is one of the most common pitfalls for beginning C programmers, it seems.

Also, you should check for the special value EOF and stop the program if it occurs; this is the typical and "clean" way of doing programs that read input and will make the program automatically handle both interactive input (from a terminal) and input from a file.

There are few observations which you might find of some use:
1. You are using getch & getche which are both non-standard functions. Make use of getchar instead. In this case as already pointed in unwind's response you need to use int for the return type.
2. Please change the return type of main from void to int .
3. You are not specifying the formats in printf . Please add %d specifier to print integers.
I have not used codepad but ideone allows you to add inputs to your programs. Here is a reference based on your sample on ideone.
Hope this helps!

#include<stdio.h>
#include<stdbool.h>

int main(void)
{
char c = '\0';
int nw = 0,nc = 0,nl = 0;

bool flag = true;
bool last = false,cur = false;

while(flag && (c = getchar())) {

    if(c != EOF)
        ++nc;
    else
        flag = false;

    if(c == '\n') nl++;

    cur = (c == EOF || c == ' ' || c == '\t' || c == '\n')?false:true;

     if(last  && !cur )
        ++nw;

    last = cur;
}


printf("\nNo of chars : %d",nc);
printf("\nNo of lines : %d",nl);
printf("\nNo of words : %d",nw);

return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM