seekg()函数失败

编程入门 行业动态 更新时间:2024-10-28 08:24:50
本文介绍了seekg()函数失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想写一些简单的代码,它将读取一个文本文件,但读取第一行两次。我认为这将像这样的简单

I am trying to write some simple code which will read a text file but reads the first line twice. I thought this would be as simple as something like this

std::ifstream file; file.open("filename", std::ios_base::in); std::string line; std::getline(file, line); // process line file.seekg(0, ios::beg); while (std::getline(file, line)) { // process line }

但是,seekg必须失败,因为第一行未处理两次。任何想法为什么?

However the seekg must fail as the first line is not processed twice. Any idea why?

请注意:这不是我遇到的问题,但它的简化版本,以便不必粘贴多个类的代码和多个函数。真正的问题涉及到文件指针被传递到多个类中的多个函数。第一个函数可以调用也可以不调用,并读取文件的第一行。第二个函数读取整个文件,但必须首先调用seekg,以确保我们在文件的开头。

PLEASE NOTE: This is not the problem I am faced with but a simplified version of it so as not to have to paste multiple classes code and multiple functions. The real problem involves a file pointer being passed to multiple functions in multiple classes. The first function may or may not be called and reads the first line of the file. The second function reads the whole file but must first call seekg to ensure we are at the beginning of the file.

我刚刚使用上面的代码来简化讨论。 / p>

I just used the code above to simplify the discussion.

推荐答案

而不是回到开头读第一行两次,我想我会用类似的东西: / p>

Rather than seeking back to the beginning and reading the first line twice, I think I'd approach things with something like:

std::ifstream file("filename"); std::string line; std::getline(file, line); process(line); do { process(line); } while (getline(file, line));

现在,假设 process 不会修改行(但如果需要,很容易为第一次调用创建一个额外的副本)。

At the moment, this assumes that process doesn't modify line (but if needed, it's easy enough to make an extra copy of it for the first call).

编辑:给定修改的要求在编辑的答案,听起来像seek真的需要。在这种情况下,在继续之前可能最干净清除流:

given the modified requirements in the edited answer, it sounds like the seek is really needed. That being the case, it's probably cleanest to clear the stream before proceeding:

std::getline(file, line); process1(line); file.seekg(0); file.clear(); process2(file);

更多推荐

seekg()函数失败

本文发布于:2023-10-07 20:06:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1470408.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   seekg

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!