C++ Program to Count the Number of Spaces in a File
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:
- Open the file which contains a string. For example, a file named “file.txt” contains the string “Geeks For Geeks”.
- Create a string variable to store the string extracted from the file.
- Create one counter variable to count the number of whitespaces in a file.
- Display the number of total whitespaces in a file.
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
fstream f1;
string ch;
int count = 0;
f1.open( "file14.txt" , ios::in);
while (!f1.eof()) {
f1 >> ch;
count++;
}
f1.close();
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
Share your thoughts in the comments
Please Login to comment...