I am counting the number of lines of a file this way

n = count(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), '\n') + 1;

After that I would like to read it in line by line, but this does not work,

while (!file.eof()) {
    string row;

    file >> row;
    cout << row << endl;
}

because I think the count moved the position to the end. If I reopen the file it works, but I guess it is ugly solution.

Is there any way/member function to return to the begining?

有帮助吗?

解决方案 2

Clear the istream of error bits and seek back to the beginning of the file. Whether this is the optimal approach to what you want to do is another question depending on what your goal really is.

int main(int argc, char *argv[])
{
    ifstream file("file.txt");

    int n = count(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), '\n') + 1;

    file.clear();
    file.seekg(0);

    string row;    

    while (file >> row)
        cout << row << endl;

    return (0);
}

其他提示

"I am counting the number of lines of a file this way ... After that I would like to read it in line by line"

You can do both of these things at once:

std::ifstream filestream("somefile.ext");
std::vector<std::string> lines;

std::string line;
while (std::getline(filestream, line)) {
    lines.push_back(line);
}
std::cout << "file has " << lines.size() << " lines" << std::endl;

Also note that:

while (!file.eof()) {
    std::string row;
    file >> row;
    ... // doing something with row
}

is not safe since >> might hit the end of the file or some error might occur so the rest of the loop's body should not rely on it being read properly. This is a good way to go:

std::string word;
while (file >> word) {
    ... // doing something with row
}

which is actually reading word by word (not line by line).

If you're using ifstream to iterate over a file, you can adjust your read position with seekg

e.g.:

std::ifstream file(...);
int linecount = 0;
while (!file.eof()) {
    if (file.get() == '\n') { ++linecount; }
}
// Clear the eofbit.  Not necessary in C++11.
file.setstate(0);  
// Rewind to the beginning of the file.
file.seekg(0);

If you're using cin, that is NOT a file. So you cannot rewind it. You can either store every line (like @LihO suggests), or rework your processing so you iterate through your input once, counting the lines as you go.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top