int main() { cout<<"Enter a String: "<<endl; //requesting a string string s; getline(cin,s); //to read space separated input int count=1; //setting count to 1 for(int i=0;i<s.length();i++){ //loop to count words if(s[i]==' '){ count++; } } cout<<"No of words: "<<count<<endl; //printing the required output return 0; }
Note: Count is set to 1 as last word won't have space after it.
0 Comments