【问题标题】:Indexing my while loop with count parameter in an array用数组中的计数参数索引我的 while 循环
【发布时间】:2010-03-04 23:58:02
【问题描述】:

我的函数采用 ifstream ofjects 数组和 ifstream 对象的数量,如下所示:

void MergeAndDisplay(ifstream files[], size_t count)

我的问题是我想使用 while 循环从文件中读取,只要其中一个文件是打开的。当我到达 eof 时,我关闭了文件。所以我想我可以做类似的事情

int fileNum = 0;
while(files[fileNum].is_open() || something here) {
//do stuff
}

但我不确定如何在我的 while 循环中放置正确数量的参数...

【问题讨论】:

    标签: c++ loops


    【解决方案1】:

    您将不得不单独计算“此集合中的任何文件是否打开”的逻辑。我建议让它成为自己的函数,这样while循环就可以干净自然,例如

    bool isAnyOpen(ifstream files[], size_t count) {
      for (size_t i = 0; i < count; ++i) {
        if (files[i].is_open()) return true;
      }
      return false;
    }
    

    那你就可以写了

    while(isAnyOpen(files, count)) {
      // Your code here
    }
    

    编辑:这是一个比 R Samuel Klatchko 发布的更通用的案例解决方案。如果你的问题很简单,只是想从所有文件中读取所有数据,那么就使用他的方法,因为它更直接。

    【讨论】:

      【解决方案2】:

      你可能想要

      while (fileNum < count && files[fileNum].is_open())
      

      条件是每当您在循环中打开新文件时增加 fileNum

      【讨论】:

        【解决方案3】:

        试试这样的:

        void ProcessStream(std::istream& input_file)
        {
        //...
        }
        
        // Your loop
        bool  a_file_is_open = true;
        do
        {
          a_file_is_open = false;
          for (unsigned int i = 0; i < MAX_FILES; ++i)
          {
            if (files[i].is_open())
            {
              a_file_is_open = true;
              ProcessStream(files[i]);
              break;
            }
          }
        } while (a_file_is_open);
        

        【讨论】:

          猜你喜欢
          • 2021-06-22
          • 2018-05-21
          • 1970-01-01
          • 2019-12-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多