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: Beginner For Beginner 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 “Beginner For Beginner”.
- 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++
// 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.
Contact Us