Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
Problem Statement - Counting words in a text input even if it is not well formed
Write a program to count number of words even when there might be extra spaces between words and extra punctuation marks. Any alphabets or numbers written contiguously will be counted as words. For. e.g. “21st Century” are two words and “21 st century systems ?” are four words. ? is not counted as word while 21 is counted as a word.
Related codes are those codes where similar programming concepts are in use. They are different from alternate codes in the sense that they may not have same purpose and results.
:
Run Output
Input a sentence (Max. 100 chars): 21st Century : A Century of Services.
No. of words in given sentences = 6
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
char str[101];
cout<<“Input a sentence (Max. 100 chars): ” ;
cin.getline(str,80);
int wc=0,j;
for(int i=0;str[i]!=”;++i)
{
j=0;
while(isalnum(str[i]))
{
if(j==0) { wc++; j=1;}
++i;
}
}
cout <<“No. of words in given sentences = “<<wc<<endl;
return 0;
}
Notes
This is a novel technique of words counting which you may not find in books. Please try this input with different kinds of sentences with numbers, punctuators, words with included numbers etc.
This technique is better than even professional word processing tools as it can ignore punctuation marks even when they have spaces in between words and punctuation marks.
This program also explains a novel looping technique where you can keep the loop count stay for some time until a particular condition is met. Such techniques are are useful when data is streaming from file or from any other streaming device.
Common Errors
The loop will not run well if the j flag is not reset before starting the internal loop.