You are here:

C++/c++ filing

Advertisement


Question
i want to know that how can i count the numbers of words, characters ,spaces and lines in a c++ file.plz rply

Answer
To read each line, use std::getline() http://www.cppreference.com/wiki/string/getline For example,

#include <string>
#include <fstream>

int main()
{
   std::ifstream file( "filename_here" ) ;
   std::string line ;
   while( std::getline( file, line ) // read lines one by one till there are none left
   {
      // do whatever with the line just read
   }
}

To get the number of characters in the line, use line.size() http://www.cppreference.com/wiki/string/size
If you also want to include the new line in the character count, add one to it.

To count the number of spaces, use the algorithm std::count_if() http://www.cppreference.com/wiki/stl/algorithm/count_if in conjunction with std::isspace() http://www.cppreference.com/wiki/c/string/isspace

To get the number of words in the line, the easiest way is to use   a std::istringstream http://net.pku.edu.cn/~course/cs101/resource/www.cppreference.com/cppsstream/all... to parse the line that is read. For example,

std::istringstream stm( line ) ;
std::string word ;
int num_words_in_line = 0 ;
while( stm >> word ) ++num_words_in_line ;

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++09. i would not answer questions about gui and web programming.

Experience

over 15 years

Education/Credentials
post graduate engineer

©2012 About.com, a part of The New York Times Company. All rights reserved.