【问题标题】:I can't read a single line using getline() [closed]我无法使用 getline() 读取单行 [关闭]
【发布时间】:2013-12-17 13:17:05
【问题描述】:

我有课:

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。 我想将它输出到控制台,但它不起作用 - 好像文件是空的(屏幕上什么都没有出现)。

【问题讨论】:

  • 您的文件是否以换行符开头?
  • 当您说屏幕上没有出现任何内容时,是否包括“ok”?如果是这样,那么 db_file.good() 返回 false,或者 db_file.open() 返回 false,或者你没有调用 couteverything()
  • 你也可以试试else { cout &lt;&lt; "not ok"; }
  • 在你的析构函数中放一个 std::clog
  • 文件在当前目录吗?

标签: c++ visual-studio-2010 file getline


【解决方案1】:

在您的构造函数中,您不测试文件是否打开成功。因此,您不知道文件是否成功打开。因此,您的 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() 和@ 987654329@ 之前 每次阅读。您需要测试getline()是否成功,否则您的代码将尝试处理超出EOF的一行或读取错误。

    if (getline(db_file, line)) { 
        cout << line;
        cout << "ok";
    } 

如果您只想一次输出一行,我不确定调用它的代码如何知道何时停止。但是,这是一个不同的问题。 (提示:您可以通过从该 line-at-a-time 方法返回 bool 来解决那个。)

【讨论】:

    猜你喜欢
    • 2018-05-17
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    相关资源
    最近更新 更多