Input sentence and count the number of words in it in C++
String Methods - Question 2
In this question, we will see how to input a sentence and count the number of words in it in C++ programming. To know more about string methods click on the string methods lesson.
Q2) Write a program in C++ to input a sentence and count the number of words in it. Assume that there may be any number of blank spaces between the words.
Program
#include <iostream>
#include <conio.h>
#include <string.h>
#include <stdio.h>
using namespace std;
int main()
{
char s[100];
int i,wc=0;
cout<<"Enter a sentence\n";
gets(s);
for(i=0; i<strlen(s); i++)
{
if(i==0 && s[i]!=' ')
{
wc++;
}
else if(s[i]==' ' && s[i+1]!=' ')
{
wc++;
}
}
cout<<"Total words = "<<wc;
return 0;
}
Output
Enter a sentence We are free to take our own decision Total words = 8