开发者

Indexing my while loop with count parameter in an array

My function takes an array of ifstream ofjects and the number of ifstream objects as seen below:

void MergeAndDisplay(ifstream files[], size_t count)

My problem is I want to use a while loop to read from the file(s) as long as one of them is open. When I get to eof, I close 开发者_开发问答the file. So I thought I could do something like

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

But I am not really sure how to put the correct amount of parameters in my while loop...


You will have to compute the logic of "is any file in this set open" separately. I suggest making it its own function so that the while loop can be clean and natural, e.g.

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

Then you can write

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

Edit: This is a more general case solution than what R Samuel Klatchko posted. If your problem is as simple as wanting to just read all the data out of all the files, then use his method since it is more direct.


You probably want

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

with the condition that you increment fileNum whenever you open a new file in your loop.


Try something like this:

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜