您的位置:首页 > 编程语言 > C语言/C++

C++计算文件的行数 不考虑空行

2013-05-26 17:13 218 查看
http://zhidao.baidu.com/question/526496386.html
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;

int main(void)
{
    ifstream file("test.txt");
    string str;
    int count = 0;
    while (file) {
        getline(file, str);//从文件中读取一行
        remove(str.begin(), str.end(), ' ');//这个算法函数在algorithm头文件中,删除一行中的空格
        remove(str.begin(), str.end(), '\t');//删除一行中的制表符,因为制表符和空格都是空的
        if (str.length() > 0) {//如果删除制表符和空格之后的一行数据还有其他字符就算有效行
            count ++;
        }
    }
    
    cout<<count;
    return 0;
}
int main(){	ifstream  infile;	infile.open("test.txt");	int word_nums=0;	int line_num=0;	if (!infile)	{		cerr<<"can't open file: "<<infile<<endl;	}		string  str;		while(!infile.eof())		{			getline(infile,str);			remove(str.begin(),str.end(),' ');//不考虑每行的空格 制表符  \n         //	remove(str.begin(),str.end(),'\n');			remove(str.begin(), str.end(), '\t');			if (str.length()>0)			{				++line_num;			}		} 		infile.close();      	infile.clear(); 	    cout<<line_num<<endl;		infile.open("test.txt");		int word;		while(infile>>word) 		{			++word_nums;			}	cout<<word_nums<<endl;	return 0;}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐