Getline()读取额外的行
getline() reads an extra line
ifstream file("file.txt");
if(file.fail())
{
cout<<"Could not open the file";
exit(1);
}
else
{
while(file)
{
file.getline(line[l],80);
cout<<line[l++]<<"n";
}
}
我使用二维字符数组来保持从文件中读取的文本(多于一行),以计算文件中的行数和单词数,但问题是getline总是读取额外的行。
你的代码,因为我写这个:
ifstream file("file.txt");
if(file.fail())
{
cout<<"Could not open the file";
exit(1);
}
else
{
while(file)
{
file.getline(line[l],80);
cout<<line[l++]<<"n";
}
}
第一次getline
失败时,仍然增加行计数器并输出(不存在的)行。
总是检查是否有错误。
额外建议:使用<string>
头中的std::string
,并使用其getline
功能。
干杯,hth .
问题是当您在文件的末尾时,对file
的测试仍然会成功,因为您还没有读取过文件的末尾。因此,您还需要测试getline()
的返回值。
由于需要测试getline()
的返回是否成功,因此不妨将其直接放在while循环中:
while (file.getline(line[l], 80))
cout << line[l++] << "n";
这样你就不需要对file
和getline()
进行单独的测试。
这将解决您的问题:
ifstream file("file.txt");
if(!file.good())
{
cout<<"Could not open the file";
exit(1);
}
else
{
while(file)
{
file.getline(line[l],80);
if(!file.eof())
cout<<line[l++]<<"n";
}
}
它更健壮
文件是否以换行符结束?如果是,EOF标志将不会被触发,直到一个额外的循环通过。例如,如果文件是
abcn
defn
然后循环将运行3次,第一次它将获得abc
,第二次它将获得def
,第三次它将一无所获。这可能就是为什么您会看到额外的一行。
尝试检查getline后流的failbit
仅在file.good()
为真时执行cout
。您看到的额外行来自对file.getline()
的最后一次调用,它读取了文件的末尾。
相关文章:
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- 为什么 getline() 不读取文本文件中的所有内容?
- 有没有办法在不使用 getline() 的情况下从.csv文件中读取?
- 当 getline 直到新行才读取时会发生什么?
- Getline在读取文本文件时有一种奇怪的行为
- 使用getline读取.csv文件时出现问题
- 如何在不循环的情况下使用getline读取文件
- 使用std::getline()读取一行
- C++ : 如何在使用 getline() 和 ifstream 对象从文件中读取一行时跳过第一个空格?
- 无法使用 getline() 输入字符串.它只读取一个字符串
- 从 txt 文件中读取数据的 Getline
- 如何使此函数使用 getline 读取字符串并使用 int 执行相同的行为?
- std::getline 读取最后一个字符串两次
- 使用 c++ 中的 getline 函数连续读取两行
- 使用 getline 读取字符串,但每行中都有换行符
- 为什么我的getline不正确读取.csv文件
- C 使用getline()内部循环以在CSV文件中读取
- 使用 getline 从输入文件读取一行到输出文件
- 使用 getline 从文件中读取多行
- 使用 getline 和 FILE 而不是 ifstream 的 c++ 读取文件