C++ Program to Count the Number of Whitespace Characters in a File

This C++ Program which counts the number of white-space characters in the file. The program creates an input file stream, reads a line on every iteration of a while loop, increments the count variable every time a white-space character (‘ ‘) or a tab-space character (‘\t’) is encountered and the count variable is printed on the screen.

Here is source code of the C++ program which counts the number of white-space characters in a file. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Count the White-Spaced Characters in a File
  3.  */
  4. #include <iostream>
  5. #include <fstream>
  6.  
  7. int main()
  8. {
  9.     int count = 0;
  10.     std::string line;
  11.     std::ifstream file("main.cpp");
  12.  
  13.     while (getline(file, line))
  14.     {
  15.         for (int i = 0; i < line.length(); i++)
  16.         {
  17.             if (line[i] == ' ' || line[i] == '\t')
  18.                 count++;
  19.         }
  20.     }
  21.     std::cout << "Number of white-space characters"
  22.               << " is " << count << "\n.";
  23.     return 0;
  24. }

$ g++ main.cpp
$ ./a.out
Number of white-space characters is 155.

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.