3

这个小的自定义 getline 函数是作为一个关于处理不同行尾的问题 的答案给出的。

该函数运行良好,直到 2 天前对其进行了编辑,以使其不会跳过每行的前导空格。但是,在编辑之后,程序现在进入无限循环。对代码所做的唯一更改是以下行:

std::istream::sentry se(is);  // When this line is enabled, the program executes
                              // correctly (no infinite loop) but it does skip
                              // leading white spaces

对此:

std::istream::sentry se(is, true); // With this line enabled, the program goes 
                                   // into infinite loop inside the while loop  
                                   // of the main function.

如果我们指定不跳过空格,有人可以帮我解释为什么程序无限循环吗?

这是完整的程序...

std::istream& safeGetline(std::istream& is, std::string& t)
{
    t.clear();

    // The characters in the stream are read one-by-one using a std::streambuf.
    // That is faster than reading them one-by-one using the std::istream.
    // Code that uses streambuf this way must be guarded by a sentry object.
    // The sentry object performs various tasks,
    // such as thread synchronization and updating the stream state.

    std::istream::sentry se(is, true);
    std::streambuf* sb = is.rdbuf();

    for(;;) {
        int c = sb->sbumpc();
        switch (c) {
        case '\r':
            c = sb->sgetc();
            if(c == '\n')
                sb->sbumpc();
            return is;
        case '\n':
        case EOF:
            return is;
        default:
            t += (char)c;
        }
    }
}

这是一个测试程序:

int main()
{
    std::string path = "end_of_line_test.txt"

    std::ifstream ifs(path.c_str());
    if(!ifs) {
        std::cout << "Failed to open the file." << std::endl;
        return EXIT_FAILURE;
    }

    int n = 0;
    std::string t;
    while(safeGetline(ifs, t))   //<---- INFINITE LOOP happens here. <----
        std::cout << "\nLine " << ++n << ":" << t << std::endl;

    std::cout << "\nThe file contains " << n << " lines." << std::endl;
    return EXIT_SUCCESS;
}

我也尝试在函数的最开始添加这一行,但没有任何区别......程序仍然在 main 函数的 while 循环中无限循环。

is.setf(0, std::ios::skipws);

文件end_of_line_test.txt是一个文本文件,仅包含以下两行:

   "1234" // A line with leading white spaces
"5678"    // A line without leading white spaces
4

1 回答 1

6

问题是safeGetLine永远不会eof()为流设置状态。

当您使用std::istream::sentry se(is);时,会尝试读取空格并发现您处于文件末尾。当您要求它不要寻找空格时,这永远不会发生。

我相信您应该is.setstate(ios_base::eofbit)为该函数添加 EOF 条件。

于 2012-02-08T07:57:15.623 回答