C++ Program to Count Number of Words in String

C++ Program to Count Number of Words in String : You will get C++ program to count number of words in string. Given a string, count the number of words in it. The words are separated by the following characters: space (‘ ‘) or newline (‘\n’) or tab (‘\t’) or a combination of these.

First we initialize a counter variable to 1. Now iterate through a string and count all the spaces, for each space increase the value of the counter.

C++ Program to Count Number of Words in String

#include<iostream>
using namespace std;
int main( )
{
	char str[80];
	cout << "Enter a string: ";
	cin.getline(str,80);
	int words = 0; 
	for(int i = 0; str[i] != '
#include<iostream>
using namespace std;
int main( )
{
char str[80];
cout << "Enter a string: ";
cin.getline(str,80);
int words = 0; 
for(int i = 0; str[i] != '\0'; i++)
{
if (str[i] == ' ') 
{
words++;
} 		
}
cout << "The number of words = " << words+1 << endl;
return 0;
}
'; i++) { if (str[i] == ' ') { words++; } } cout << "The number of words = " << words+1 << endl; return 0; }

Output of Program

Enter a string: 40
The number of words = 1