如何计算文本文件中的行数。 我尝试使用以下代码,但输出始终为0。 用户将输入他/她想要读入的.txt文件,然后程序将计算文件中的行数。
编辑:
ifstream in (infile.c_str(), ios::in);
if(!in.is_open())
{
cout << "Error - opening file: " << infile << endl;
return;
}
while(!in.eof())
{
in >> type;
if(in.fail()) break;
//read corresponding object
if(type == "Point2D,")
{
in >> p2d;
//add to container
points2d.push_back(p2d);
}
else if(type == "Point3D,")
{
in >> p3d;
//add to container
points3d.push_back(p3d);
}
else if(type == "Line2D,")
{
in >> line2d;
//add to container
lines2d.push_back(line2d);
}
else if(type == "Line3D,")
{
in >> line3d;
//add to container
lines3D.push_back(line3d);
}
}
in.close();
while (getline(in, line))
++noOfRec;
cout << noOfRec<<" records reading successfully!" << endl;
//return 0;
答案 0 :(得分:2)
in.close();
您已经关闭了该文件。 你应该再次打开它或者使用seekg()
放回指向文件开头的指针答案 1 :(得分:0)
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() // <-------- HERE
{
int c=0;
string s;
cin >> s; // include extension
fstream input(s.c_str());
while (getline(input, s))
c++;
cout << c << endl;
return 0;
}