Ads 468x60px

Saturday 10 December 2011

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

This is a simple C++ program that counts the number of words in a line or a string. Each word is separated by a space and the string will be entered by the user. The program can be designed as follows:

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

Sourcewww.LearnCandCpp.com
If you have any problem regarding this program, you may leave your comment below.

2 comments:

vrshn said...

i get an error saying, gets() should have a prototype. what does it mean?

Ankit Sharma said...

Hello Geetha,
You I have answered your question here:
Count number of words in a string or a line.
Actually the above program is missing the use of Header files. The correct header files can be seen from the above link.

Post a Comment