c++ - 计算文件中的换行符

标签 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();
}

最佳答案

改变:

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 的文档.

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

相关文章:

c++ - boost::hash_combine 中的魔数(Magic Number)

c++ - 为什么复制构造函数 "chained"不像默认构造函数和析构函数?

c++ - Boyer Moore k-mismatches 算法失败

Ruby 字符串剥离定义的字符

c# - 存储在字符串变量中的值在每次页面加载时丢失

c++ - 如何使用 oledb 使用其各自的 .dbc 文件从 .dbf 文件读取/写入数据?

c++ - 自Windows 10 20H1起,多个具有单独线程的窗口停止工作

c - 在 C 中通过定界符函数实现拆分字符串

java - 从可以按单词分割然后在 Java 中附加的字符串返回 List<String>

c++ - std::string::back()