c++ - 计算文本文件C++中的行数

标签 c++

如何计算文本文件中的行数。 我试过以下代码,但输出始终为 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;

最佳答案

 in.close();

您已经关闭了文件。 您应该再次打开它或使用 seekg() 将获取指针放回文件开头

关于c++ - 计算文本文件C++中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20028326/

相关文章:

c++ - 整数常量与类型的偏特化

c++ - 在 Boost 中执行深度优先搜索和广度优先搜索

c++ - 线程所有权

c++ - 将 float 类型更改为 short 但具有与 float 类型变量相同的行为

c++从ostream获取一个字符串(序列化对象)

c++ - std::vector::erase(item) 需要为项目定义赋值运算符?

C++ 包装器模板 : how to pass it as a template parameter?

c++ - 智能指针和 dynamic_cast

c++ - 如何在 C++ gSOAP 生成的类中使用 SSL

c++ - 我应该如何递归调用模板函数?