Here we will be counting total number of words in a string. It will be somewhat lengthy than a straight solution because we have to take care of spaces at the start and at the end.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
#include <iostream.h> #include <conio.h> #include <string.h> void main(){ int i,wordsi,wordc=0,pos; char string[1000],words[100][30]; clrscr(); cout << "Enter the paragraph"<<endl; cin.getline(string,1000); cout <<endl; for(i=0;i<strlen(string);){ //strip any spaces at the start (not actually but logically) if(i==0){ if((int)string[0]==32){ while((int)string[i]==32) { i++; } } } //now start counting words if((int)string[i]==32){ wordc++; while((int)string[i]==32){ i++; } } else { i++; } } // add an extra count due to count of space between // words is one less than the total words if((int)string[strlen(string)-1]==32) { } else { wordc++; } cout << wordc; */ getch(); } |
Compiled by TurboC3