ifstream& operator>>函数无法获取空行
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string str;
ifstream fin("c:\\1.txt"/*, ios::binary*/);
if(!fin.is_open())
{
cout<<"打开失败\r\n";
return 0;
}
if (fin.peek() == EOF)
{
cout << "file is empty."<<endl;
return 0;
}
int count=0;
while (!fin.eof())
{
fin >> str;
cout << str<<endl;
count++;
}
system("pause");
return 0;
}
peek函数才能够做到防止空文件的出现
本文探讨了使用C++标准库中的ifstream与运算符重载进行文件读取时遇到的问题,特别是当文件包含空行时istream提取运算符的行为。文中提供了一个简单的示例程序来展示如何检查文件是否为空,并尝试读取文件内容。
6277

被折叠的 条评论
为什么被折叠?



