Tuesday, 5 April 2016

Write a program to count number of words in string C++ Problem Solution.


Solution:

#include<bits/stdc++.h>
using namespace std;
/*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){

    string str;
    int words = 0; // Holds number of words

    cout << "Enter a string: ";
    getline(cin,str);

    for(int i = 0; i < str.size(); i++){
 if(str[i] == ' ')words++;   //Checking for spaces
    }
    cout << "The number of words = " << words+1 << endl;

    return 0;
}

No comments:

Post a Comment