从文件中读取行数,单词数,字符数 [英] Read number of lines, words, characters from a file

查看:105
本文介绍了从文件中读取行数,单词数,字符数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用以下方法轻松读取行数:

I can read the number of lines easy, using:

ifstream in(file);
string content;
while(getline(in, content))
{
   // do stuff
}

或者我可以使用类似的方法轻松阅读单词和字符的数量:

Or I can read the number of words and characters easy using something like:

ifstream in(file)
string content;
int numOfCharacters = 0;
int numOfWords = 0;
while(in >> content)
{
   ++numOfWords;
   numOfCharacters += content.size();
}

但是我不想两次读取文件.如何读取文件一次,并找出行数,单词数和字符数?

But I dont want to read the file twice. How can I read the file once, and find out the number of lines, words and characters?

PS:如果有简单的方法,我将欢迎您使用Boost.
谢谢.

PS: I would welcome a Boost sugestion, if there is a easy way.
Thank you.

推荐答案

阅读该行,并为每一行计数单词.请参阅第二部分的stringstream.

Read the line and for each line count the words. See stringstream for the second part.

(我没有提供更多信息,这看起来太像一项家庭作业).

(I'm not giving more information, that looks too much like an homework).

这篇关于从文件中读取行数,单词数,字符数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆