karthik gorijavolu
karthik gorijavolu

Reputation: 860

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

}

Upvotes: 3

Views: 19073

Answers (3)

cyberjog
cyberjog

Reputation: 1

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

Upvotes: 0

another.anon.coward
another.anon.coward

Reputation: 11405

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!

Upvotes: 1

unwind
unwind

Reputation: 400129

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.

Upvotes: 3

Related Questions