<分区>
关于您编写的代码问题的问题必须在问题本身中描述具体问题 — 并且包括有效代码 以重现它。参见 SSCCE.org 寻求指导。
我有一个类:
class DataBase{
private:
fstream db_file;
public:
DataBase(){
db_file.open("db.txt", std::ios::in | std::ios::out);
}
void couteverything(){
string line;
if(db_file.good() && db_file.is_open()){
getline(db_file, line);
cout << line;
cout << "ok";
}
}
~DataBase(){
db_file.close();
}
};
和一个包含一些内容的文件 db.txt。
我想将它输出到控制台,但它不起作用 - 就好像文件是空的(屏幕上什么也没有出现)。
在您的构造函数中,您不测试文件是否成功打开。因此,您不知道文件是否成功打开。因此,您的 couteverything
方法无法将 EOF 与“打开失败”区分开来。您可以考虑添加一张支票:
DataBase(){
db_file.open("db.txt", std::ios::in | std::ios::out);
if (!db_file.is_open() || !db_file.good()) {
// put an error message here, or throw an exception. Up to you.
}
}
进入couteverything()
后,您可能想要遍历整个文件。为此,您需要一个循环,而不是 if
语句。像这样:
while (getline(db_file, line)) {
cout << line;
cout << "ok";
}
即使您不想在此处循环(在这种情况下,coutnextline()
可能是该方法的更好名称),您仍想测试 getline() 的结果
直接,而不是在每次读取之前测试 good()
和 is_open()
。您需要测试 getline()
是否成功,否则您的代码将尝试处理超出 EOF 的一行或读取错误。
if (getline(db_file, line)) {
cout << line;
cout << "ok";
}
如果您一次只想输出一行,我不确定调用它的代码如何知道何时停止。但是,这是一个不同的问题。 (提示:您可以通过从这种一次一行的方法返回一个 bool
来解决那个 。)