更新时间:2023-11-27 22:04:16
你还应该测试ifstream
读完角色后立即,即
You should also test theifstream
immediately after reading the character, namely
//..
infile.get(ch);
if ( infile.good() ) outfile.put(ch);
// ..
之前的解决方案虽然完全正确,但并不能解释为什么第二次测试是必要的。以下是完整的故事:
在您阅读了流的最后一个字符后,
The previous solution, although entirely correct, does not explain why that second test is necessary. Here is the full story:
After you have read the last character of the stream by
infile.get (ch);
流在文件结束状态尚未。所以下一个循环迭代仍然会发生。只有在尝试读取流结束之后才会设置流中的eof标志。在最后一次迭代中,其中get命中文件结尾,ch将被设置为值EOF而不是有效字符。那个EOF值(通常是-1)就是你在输出中看到的。
实际上你可以用这样的一个测试编写你的循环:
the stream is not yet in the end-of-file state. So the next loop iteration will still occur. Only after get attempts to read beyond the stream end the eof flag in the stream will be set. In that last iteration, in which get hits the end-of-file, ch will be set to the value EOF instead a valid character. And that EOF value (usually a -1) is what you see in your output.
In fact you could have written your loop with only one test like this:
while (true)
{
infile.get (ch);
if (!infile.good())
break;
outfile.put (ch);
}