简体   繁体   中英

Failed reading file after “istreambuf_iterator”

I wanted to find the number of lines in a text file but I failed to read the content after executing 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 ;

What did I do wrong?

You read to the end of the file, so it's not surprising there are no values left to read. You need to reset your read pointer if you intended to read that value from the beginning of the file:

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

It's a little unusual to do a line count like this and then go back to read data, as it cannot be translated to a generic stream (for example if your program was to receive data on standard input). If parsing is line based, the following pattern is commonly used:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM