Friday 2 March 2012

C++ program that counts the number of words in a string or a line


This is a C++ program, with the help of which you can find out how many words are there in a string or a line. Below is the coding.

#include "iostream.h"
#include "conio.h"
#include "string.h"
main()
{
 char str[50];
 int i, count = 1;
 cout << "\n\t Enter the string ";
 gets(str);
 while((str[i]!= '\0') && (str[i+1] != ' '))
 {
  if ((str[i] == ' ') || (str[i] == '.'))
  count++;
  i++;
 }
 cout << "\n\t Number of words in a string is " << count;
 return 0;
}

Step by step explanation: 
1. Header files used are iostream.h for input and out put functions, conio.h is used for functions like getch() and clrscr(), and string.h is used for function gets() and other string related function. If you don't use any of the above header file. The possible error which may come is : "X function should have prototype", where X can be any function.
2. main() function is starting of every function. All working, calls and loops are defined under main function only.
3. gets() function can be treated as an alternative of cin, when the case comes for string.
If you find any difficulty in understanding the program, or you have any proble, you may post your comment below.

1 comment:

  1. Great code, thanks for the share. It was just what I was looking for.

    ReplyDelete