Open In App

C++ Program to Count the Number of Spaces in a File

Improve
Improve
Like Article
Like
Save
Share
Report

Here, we will see how to count number of spaces in a given file. First, we will read the contents of the file word by word, keep one counter variable ‘count’, and set it to zero while declaring. Increment ‘count’ each time you read a single word from the file.

Example:

Input: Geeks For Geeks
Output: There are 2 whitespaces in file 

Approach:

  1. Open the file which contains a string. For example, a file named “file.txt” contains the string “Geeks For Geeks”.
  2. Create a string variable to store the string extracted from the file.
  3. Create one counter variable to count the number of whitespaces in a file.
  4. Display the number of total whitespaces in a file.

C++




// C++ program to demonstrate the
// number of whitespaces in a
// file
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    // filestream variable
    fstream f1;
 
    // string variable
    string ch;
 
    // counter variable
    int count = 0;
 
    // opening file for reading contents
    f1.open("file14.txt", ios::in);
 
    while (!f1.eof()) {
        // extracting words from file
        f1 >> ch;
 
        // incrementing counter variable
        count++;
    }
    f1.close();
 
    // displaying total number of whitespaces in a file
    cout << "There are"<<--count<<" whitespaces in file";
    return 0;
}


Output:

There are 2 whitespaces in file

Note: We have decrementing counter variable while displaying because the C++ also reads the newline comes at the end of the file. We want an only the number of whitespaces, not newlines.


Last Updated : 01 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads