Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/137.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;fstream:到达eof时引发异常_C++ - Fatal编程技术网

C++ C++;fstream:到达eof时引发异常

C++ C++;fstream:到达eof时引发异常,c++,C++,我想读两个文件,直到读到其中一个文件的末尾。 如果出现问题,fstream应该抛出异常 问题是,设置eof位时也会设置坏位或失败位 ifstream input1; input1.exceptions(ios_base::failbit | ios_base::badbit); input1.open("input1", ios_base::binary | ios_base::in); ifstream input2; input2.exceptions(ios_base::failbit

我想读两个文件,直到读到其中一个文件的末尾。 如果出现问题,fstream应该抛出异常

问题是,设置eof位时也会设置坏位或失败位

ifstream input1;
input1.exceptions(ios_base::failbit | ios_base::badbit);
input1.open("input1", ios_base::binary | ios_base::in);

ifstream input2;
input2.exceptions(ios_base::failbit | ios_base::badbit);
input2.open("input2", ios_base::binary | ios_base::in);

ofstream output;
output.exceptions(ios_base::failbit | ios_base:: badbit);
output.open("output", ios_base::binary | ios_base::out | ios_base::trunc);

char in1, in2, out;

while(!input1.eof() && !input2.eof()) {
    input1.read((char*) &in1, 1);
    input2.read((char*) &in2, 1);
    out = in1^in2;
    output.write((const char*) &out, 1);
}

input1.close();
input2.close();
output.close();
这导致了

$ ./test
terminate called after throwing an instance of 'std::ios_base::failure'
  what():  basic_ios::clear

如何正确操作?

如果(fstream)检查所有位(eof坏和失败),只需删除
.eof()

因此,将while改写为:

 while(input1 && input2)
然后验证eof()对于最后一个流是否返回true


希望这有帮助。

不要抛出任何异常,使用
input1。在您的while条件下读取
istream::get

while (input1.get(in1) && input2.get(in2)) {
...
}

如果读取循环体中的字符,则输出中将有一个附加字符,而没有相应的输入字符。也许这就是您首先使用
std::ios::exeptions
的原因。

您的代码中的基本问题是。决不能将
eof()
用作读取循环的测试条件,因为在C/C++中(与其他一些语言不同)
eof()
在读取文件末尾之前不会设置为true,因此循环体将被多次输入

惯用的正确程序是将读取操作本身置于循环条件下,以便在正确的点处退出:

  while ( input1.get(in1) && input2.get(in2) ) { /* etc */ }
  // here, after the loop, you can test eof(), fail(), etc 
  // if you're really interested in why the loop ended.

这个循环将随着较小的输入文件的耗尽而自然结束,这正是您想要的。

我们是否认为“处理异常抛出自己”的明显答案是不可能的?输入文件是否存在?可能重复:谢谢,但这段代码在到达文件末尾时仍然抛出异常。这是因为您请求了异常。关键是,您根本不需要任何异常来检测输入结束。此外,您真的不想在这个API中使用异常。参见,例如,和上述代码片段的更新