我正在尝试编写一个递归函数,它在我为类作业打开的文件中进行一些格式化。这是我到目前为止写的:
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() 函数中。那是我一次从文件中读取一个字符的方式吗?谢谢。
最佳答案
你最好使用这个:
char Reverse(ifstream &inFile) {
char myInput;
while (inFile >> myInput) {
...
}
}
人们经常忽视的一点是,您可以通过仅测试流对象来简单地测试输入流是否已达到 EOF(或其他一些错误状态)。它被隐式转换为 bool
,istreams
运算符 bool()
只是调用(我相信)istream::good()
。
将此与流提取运算符始终返回流对象本身这一事实相结合(以便它可以与多个提取链接,例如“cin >> a >> b”),您将得到非常简洁的语法:
while (stream >> var1 >> var2 /* ... >> varN */) { }
更新
抱歉,我没有考虑 - 当然这会跳过空格,这不适用于您反转文件内容的示例。最好坚持使用
char ch;
while (inFile.get(ch)) {
}
它还返回 istream 对象,允许隐式调用 good()
。
关于c++ - C++ 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2111474/