【问题标题】:How to read just before EOF from a file and put it into a string? [duplicate]如何在 EOF 之前从文件中读取并将其放入字符串中? [复制]
【发布时间】:2020-05-04 19:03:09
【问题描述】:

我的函数读取一个文件并将其放入一个字符串中以便我处理它。显然,我需要在 EOF 之前阅读。问题是 EOF 字符也放在字符串中,我找不到绕过它的方法,因为它会导致程序的其他部分失败。我链接下面的函数。

    string name_to_open, ret = string();
    ifstream in;

    getline(cin, name_to_open);
    in.open(name_to_open.c_str());
    if (!in.is_open()) {
        cout << "Error." << endl;
        return string();
    }
    else {
        ret += in.get();
        while (in.good()) {
            ret += in.get();
        };
    };
    in.close();
    return ret;

该函数可以正常读取到文件末尾,然后附加 EOF 和 \0。我该如何解决这个问题? EOF 字符在控件中工作正常吗?我还尝试在循环结束时添加一行ret[ret.size() - 1] = '\0';,但这似乎也不起作用。

【问题讨论】:

  • 你怎么看这个“EOF字符”?

标签: c++ eof


【解决方案1】:

ret += in.get(); 将从磁贴读取的字符附加到字符串中,无论读取的值是否正确。您需要 1) 读取,2) 测试读取是否有效并且读取的值可以安全使用,3) 使用读取的值。目前,您的代码会读取、使用并测试读取的值是否可以安全使用。

可能的解决方案:

int temp;
while ((temp = in.get()) != EOF) // read and test. Enter if not EOF
{
    ret += static_cast<char>(temp); // add the character
};

注意:get 返回 int,而不是 char。这是为了能够插入诸如 EOF 之类的带外代码,而不会与现有的有效字符发生冲突。立即将返回值视为char 可能会导致错误,因为可能会错误处理特殊代码。

注意:将整个文件读入字符串有很多更好的方法:How do I read an entire file into a std::string in C++?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 2012-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多