C++ Programming

Write a C++ program to count all the characters, blank spaces and words in a given string.

Method 1

#include <iostream>
#include <string>

using namespace std;

int main() {
  string str;
  //Give the initials
  int characterCount = 0, wordCount = 0, blankSpaceCount = 0;

  cout << "Enter any sequence of words or line: ";
  getline(cin, str); 

  for (char c : str) {
  characterCount++; 
  if (c == ' ') {
      blankSpaceCount++;
    }
  }
  //Words should be separated by single space
  wordCount = blankSpaceCount + 1; 

  cout << "Number of characters: " << characterCount << endl;
  cout << "Number of words: " << wordCount << endl;
  cout << "Number of blank spaces: " << blankSpaceCount << endl;

  return 0;
}

Output

Enter any sequence of words or line: Coddesire is for programming and technology
Number of characters: 43
Number of words: 6
Number of blank spaces: 5

Method 2

#include <iostream>
#include <string>

using namespace std;

//Function to count character words and space
void count(const std::string& input, int& charCount, int& wordCount, int& spaceCount) {
    
    bool inWord = false;
    for (char ch : input) {
//Words should be separated by a single space
        if (ch != ' ') {
            charCount++; 
            if (!inWord) {
            wordCount++; 
            inWord = true;
        }
        } else {
            spaceCount++; 
            inWord = false; 
        }
    }
}

int main() {
    string input;
    cout << "Enter any sequence of words or line: ";
    getline(cin, input);

    //Give the initials
    int charCount = 0, wordCount = 0, spaceCount = 0;

    count(input, charCount, wordCount, spaceCount);

    cout << "Number of characters : " << charCount <<endl;
    cout << "Number of words: " << wordCount <<endl;
    cout << "Number of spaces: " << spaceCount <<endl;

    return 0;
}

Output

Enter any sequence of words or line: CodDesire is for programming and technology
Number of characters : 38
Number of words: 6
Number of spaces: 5
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments