【问题标题】:Reading from a file in C++从 C++ 中读取文件
【发布时间】:2011-01-07 20:42:05
【问题描述】:

我正在尝试编写一个递归函数,该函数在我为课堂作业打开的文件中进行一些格式化。这是我到目前为止所写的:

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() 函数。那是我一次从文件中读取一个字符的方式吗?谢谢。

【问题讨论】:

    标签: c++ file-io stream


    【解决方案1】:

    你最好使用这个:

    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()

    【讨论】:

      【解决方案2】:
      void Reverse(ifstream &inFile) {
          char myInput;
          while ( inFile.get( myInput ) ) {
             // do something with myInput
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2014-04-02
        • 2012-05-15
        • 2016-06-18
        • 2016-08-02
        • 2020-11-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多