比较从文件读取整数的不同方式 [英] On comparing different way of reading an integer from a file

查看:176
本文介绍了比较从文件读取整数的不同方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读此问题时,我发现在回答不同的读取整数的方式。以下是其中两个。

While reading this question, I found in the answers different way of reading an integer. Here are two of them.

来自πάνταῥεῖ的回答

if(iFile) {
    iFile >> int1;
    cout << "From first file:" << int1 << endl;
}

JRowan的回答

if(!iFile.eof()){
    iFile >> int1; 
    cout << "From first file:" << int1 << endl;
}

但我想知道如果使用下面的代码等同于上面的两个?还有,是否有任何理由不使用三个示例代码之一?

But I was wondering if using the code below is equivalent to the two above? Also, is there any reason not to use one of the three sample codes?

if (iFile >> int1) {
   cout << "From first file:" << int1 << endl;
}

感谢。

推荐答案

在构建 ifstream 对象 iFile 没有错误。这可以通过在C ++和C ++ 11中简单地做 if(iFile)来正确完成。假设你已经做了这个检查,第三个代码片段是从文件读取ints的唯一正确的方法。前两种方法最终会在 eof 之前打印最后一个整数。这是因为他们在执行 iFile>> int1 后不检查流的状态。所以,如果他们遇到eof,你不会知道并继续调用 cout

On constructing the ifstream object iFile, you should check that there were no errors. This is correctly accomplished by simply doing if(iFile) in both C++ and C++11. Assuming you have already done this check, the third code snippet is the only correct way of reading the ints from file. The first two methods will end up printing the last integer before eof twice. This is because they don't check the state of the stream after doing iFile>>int1. So, if they had encountered eof, you wouldn't know and continue to call cout.

这篇关于比较从文件读取整数的不同方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆