我正在尝试读取文本文件中的换行数。但是,我的计数器不工作。是因为字符串比较吗?
#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/