Users Online

· Guests Online: 5

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

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

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.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.84 seconds
10,924,795 unique visits