C++/c++ filing
Expert: vijayan - 6/8/2010
Questioni want to know that how can i count the numbers of words, characters ,spaces and lines in a c++ file.plz rply
AnswerTo 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 ;