gpt4 book ai didi

c++ - stream seekg() 实现从 VS2012 到 2010 各不相同

转载 作者:行者123 更新时间:2023-11-30 04:21:05 24 4
gpt4 key购买 nike

我有一段在 gcc、VS2010 上运行良好的旧代码。我试图在 VS2012 中编译相同的内容。我知道我已经在任何地方将 done 设置为 true,但它不是实际代码。我已经缩短了重现问题的代码。

std::ifstream file_stream;
file_stream.open("C:\\experiment\\file.txt", std::ios_base::in);
std::istream& stream = file_stream;
bool done = false;
while(stream.good() || !done){
int stream_position = stream.tellg();
bool stream_failure = (stream_position == -1);
bool stream_eof = stream.eof();
std::string line;
std::getline(stream, line);

std::cout << stream_failure << stream_eof << std::endl;

std::streampos pos = stream.tellg();
if(pos == std::streampos(-1)){
std::streampos copy = pos;
stream.seekg(0, std::ios_base::end);
pos = stream.tellg();
stream.seekg(copy);
}
}
std::getline(std::cin, std::string());
file_stream.close();

如果我将平台工具集更改为 VS2010,它会工作并打印 1 代替 stream_eof
如果我将平台工具集更改为 VS2012,它不会打印 0 代替 stream_eof在它到达 EOF 之后

如果我在 cout 之后放置一个 if(stream_eof)return 0; 它在 VS2010 上返回但在 VS2012 上不返回

最佳答案

这是C++03和C++11的区别之一。

在 C++03 中,当您在设置了任何错误位的流上调用 seekg() 时,它会失败并且不会执行任何其他操作。

在 C++11 中,seekg() 首先无条件地清除 eofbit,然后尝试按照指示去做。在这种情况下,由于 failbit 也被设置,它失败了,但是 eofbit 被清除。

(顺便说一句,为什么你的循环设置为首先读取文件末尾?使用通常的 while(getline(stream, line)))

关于c++ - stream seekg() 实现从 VS2012 到 2010 各不相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14790299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com