从C++中的文件中读取
问题描述:
我正在尝试编写一个递归函数,该函数会在为类分配打开的文件中执行一些格式化操作。这是我迄今为止写的:从C++中的文件中读取
const char * const FILENAME = "test.rtf";
void OpenFile(const char *fileName, ifstream &inFile) {
inFile.open(FILENAME, ios_base::in);
if (!inFile.is_open()) {
cerr << "Could not open file " << fileName << "\n";
exit(EXIT_FAILURE);
}
else {
cout << "File Open successful";
}
}
int Reverse(ifstream &inFile) {
int myInput;
while (inFile != EOF) {
myInput = cin.get();
}
}
int main(int argc, char *argv[]) {
ifstream inFile; // create ifstream file object
OpenFile(FILENAME, inFile); // open file, FILENAME, with ifstream inFile object
Reverse(inFile); // reverse lines according to output using infile object
inFile.close();
}
我的问题是在我的Reverse()函数中。我是如何从文件中一次读取一个字符的?谢谢。
答
void Reverse(ifstream &inFile) {
char myInput;
while (inFile.get(myInput)) {
// do something with myInput
}
}
答
你会更好使用这样的:
char Reverse(ifstream &inFile) {
char myInput;
while (inFile >> myInput) {
...
}
}
人们常常忽视的是,你可以简单地测试是否输入流已经只是测试的流对象EOF击(或其他一些不好的状态)。它隐含地转换为bool
,而istreams
运算符bool()
只是调用(我相信)istream::good()
。
将此与流提取操作符始终返回流对象本身(以便它可以与多个提取进行链接,如“cin >> a >> b”)相结合,并且您到达非常简洁语法:
while (stream >> var1 >> var2 /* ... >> varN */) { }
UPDATE
对不起,我没有想到 - 当然这将跳过空格,这不会为你的倒车文件的内容的例子工作。最好在使用
char ch;
while (inFile.get(ch)) {
}
也返回IStream对象,允许good()
的隐式调用坚持。