Skip to content
Related Articles
Open in App
Not now

Related Articles

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

Improve Article
Save Article
  • Last Updated : 01 Aug, 2022
Improve Article
Save Article

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.


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


  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++ 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"file14.txt", ios::in);
    while (!f1.eof()) {
        // extracting words from file
        f1 >> ch;
        // incrementing counter variable
    // displaying total number of whitespaces in a file
    cout << "There are"<<--count<<" whitespaces in file";
    return 0;


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.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!