如何打开文件

时间:2016-05-05 17:24:30

标签: c++ file

我在尝试打开文件时遇到了一些麻烦,所以有人可以解释这个while循环是如何工作的:

#include <fstream>

std::ifstream infile("thefile.txt");
int a,b;
while (file >> a >> b){}

2 个答案:

答案 0 :(得分:2)

while循环有一个空体。因此,它所做的只是评估表达式file >> a >> b,直到它变为假

file>>a>>b从您打开的文件中读取两个整数。如果遇到错误或文件结尾,则为false。

修改

但是你在打开文件时提到了问题。在这里你可以检查它是否成功,或者它失败的原因:

if (!file) 
   cerr<<"Couldn't open the file:"<< strerror(errno) <<endl;  // or alternatively
                                                              // use the good old perror()
else 
   ...

答案 1 :(得分:1)

实际上不清楚你在问什么。如何正确打开文件,或#include <fstream> std::ifstream infile("thefile.txt"); // Tries to open the file in the current working // directory the program is executed int a,b; while (file >> a >> b){} // Will try to read numeric values from file and store them to // a and b. If the file couldn't be opened, or the parsing // for numeric values failed, the loop will never be entered or // immediately end 无法正常打开时的工作方式。

好吧,试着解释一下评论中的代码:

{{1}}