gpt4 book ai didi

c++ - 输入流迭代器和异常

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:06:10 25 4
gpt4 key购买 nike

几天前我在玩 istream 迭代器和异常处理,我遇到了这种好奇:

#include <iostream>
#include <fstream>
#include <iterator>
#include <algorithm>

using namespace std;

int main(int argc, char* argv[])
{
if (argc < 2) {
cout << argv[0] << " <file>" << endl;
return -1;
}

try {
ifstream ifs(argv[1]);
ifs.exceptions(ios::failbit | ios::badbit);
istream_iterator<string> iss(ifs), iss_end;
copy(iss, iss_end, ostream_iterator<string>(cout, "\n"));
}
catch (const ios_base::failure& e) {
cerr << e.what() << endl;
return -2;
}

return 0;
}

为什么在读取输入文件的最后一个字后总是引发 failbit 异常?

最佳答案

failbit 在读取操作未能提取任何字符时设置,无论这是因为它是否命中 EOF。

stringstream ss ("foo");
string s;
int i;

ss >> i; // sets failbit because there is no number in the stream
ss.clear();
ss >> s; // sets eofbit because EOF is hit
ss.clear();
ss >> s; // sets eofbit and failbit because EOF is hit and nothing is extracted.

关于c++ - 输入流迭代器和异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2363581/

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