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.
Input: Geeks For Geeks Output: There are 2 whitespaces in file
- 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.
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.