计算文件中的换行符

时间:2013-11-21 11:25:09

标签: c++ string

我正在尝试读取文本文件中的换行符数。但是,我的柜台不起作用。是因为字符串比较吗?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;



int main()
{
    string line;
    ifstream myFile;
    int temp_height = 0;

    myFile.open("Levels.txt");


    while (!myFile.eof())
    {
        getline(myFile,line);

        if (line == "\n") 
            temp_height++;

    }

    cout<<"\n Newlines: "<<temp_height;
    myFile.close();
}

1 个答案:

答案 0 :(得分:2)

变化:

while (!myFile.eof())
{
    getline(myFile,line);

while (getline(myFile, line))
{

这意味着您在检查之前实际上正在阅读,并且还要检查其他故障。你几乎从不想真正检查eof,它可能不会像你期望的那样工作。

编辑:好的,你想要空行。 getline会丢弃'\n'字符,因此请检查

if (line.empty())

最终循环:

while (getline(myFile, line))
{
    if (line.empty())
        ++temp_height;
}

您可以找到std::getline here的文档。