"istreambuf_iterator" 后读取文件失败

Failed reading file after "istreambuf_iterator"

我想查看一个文本文件的行数,但是执行后无法读取内容istreambuf_iterator

std::ifstream loadfile("file.txt");
line_count = std::count(std::istreambuf_iterator<char>(loadfile), std::istreambuf_iterator<char>(), '\n');
double val;
loadfile >> val ;

我做错了什么?

您已读到文件末尾,因此没有剩余值可供读取也就不足为奇了。如果您打算从文件开头读取该值,则需要重置读取指针:

loadfile.seekg( 0, std::ios::beg );

像这样进行行计数然后返回读取数据有点不寻常,因为它无法转换为通用流(例如,如果您的程序要在标准输入上接收数据)。如果解析是基于行的,通常使用以下模式:

int line_count = 0;
for( std::string line; std::getline( loadfile, line ); )
{
    ++line_count;
    std::istringstream iss( line );

    // Read values on current line from 'iss'.
}

// Now that you're finished, you have a line count.