Write a C++ program to count number of words in string.
#include<iostream>
using namespace std;
int main( )
{
int i;
int words = 0; // Variable to holds number of words
char name[30];
cout << "Enter a string to count number of words in it: ";
cin.getline(name, 30);
for(i = 0; name[i] != '\0'; i++)
{
if (name[i] == ' ') // to Check for spaces
{
words = words + 1;
}
}
cout << "Total number of words in string is = " ;
cout<< words+1
cout<< endl;
return 0;
}
Program output is tested on www.jdoodle.com
Output:
Enter a string to count number of words in it: Mukesh Rajput
Total number of words in string is = 2
Thanks
Mukesh Rajput
Post A Comment:
0 comments: