我有一些麻烦试图打开一个文件,以便能有人解释这个while循环是如何工作在这里:如何打开文件
#include <fstream>
std::ifstream infile("thefile.txt");
int a,b;
while (file >> a >> b){}
我有一些麻烦试图打开一个文件,以便能有人解释这个while循环是如何工作在这里:如何打开文件
#include <fstream>
std::ifstream infile("thefile.txt");
int a,b;
while (file >> a >> b){}
的while
环有一个空的机构。因此,它将执行的所有操作都是评估表达式file >> a >> b
,直到它变为false
file>>a>>b
从您打开的文件中读取两个整数。如果遇到错误或文件结束,它将是错误的。
编辑:
但在打开文件时你提到的问题。在这里你可以检查它是否成功,或为什么它失败:
if (!file)
cerr<<"Couldn't open the file:"<< strerror(errno) <<endl; // or alternatively
// use the good old perror()
else
...
因此,它将找到的前两个数字排序为a和b? – Irene
@Irene它不排序,它只是读取一系列两个空格分隔的整数到'a'和'b',直到到达文件末尾或者直到它遇到错误。 –
它遇到的第一个数字将在a中,第二个在b中,那么它会再次出现,所以第三个数字将在a中,第四个在b中,依此类推... – Christophe
这实际上不清楚你问的是什么。如何正确打开文件,或无法正确打开while (file >> a >> b)
时的工作方式。
好了,试图解释在注释代码:难道你不明白它是什么
#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
? – NathanOliver
在while循环之前检查'infile'的状态。 'thefile.txt'可能不在您当前的工作目录中。 –
我无法理解这是如何工作的。文件>> a >> b做什么 – Irene