Hey Guys,
i'm new to the forum and I would appreciate any help.
I'm writing a program where the user needs to choose 5 numbers from 56. At the same time I'm using loop screen out numbers outside of this range.

As a result only the 1st number out of 5 is written into file. Where's the mistake?

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
int pick[5]={0};
ofstream outputfile;
bool correct = false;
int index=0;
cout <<"Please,enter the number in the range of 1 to 56\n"<<endl;

cout<<" Enter number "<< index+1<<" out of 5:";
cin>> pick[index];
if (pick[index]<56)
cout << "You choice is outside of the range.\n Please choose number from 1 to 56.\n";
while( !correct );


I would recommend moving the file open and close operations out of the loop; even if it were working, the way you are repeatedly opening the file causes the file position to get reset each time, with the result that each number would overwrite the previous, causing only the last number to be in the file at the end.

Also, opening, closing and writing to files are fairly expensive operations, relatively speaking, and it actually makes more sense to have two separate loops - one for collecting the data, and a separate one for writing to the file. While this may seem like an inefficient approach, it is actually a lot more efficient than making separate file writes, as writes made in quick succession will generally be buffered and end up written together, something that won't happen if you keep opening and closing the file.

Edited 4 Years Ago by Schol-R-LEA: n/a

It worked.
First, I did 2 separate loops for collecting the data and writing the file. I thought that approach was more inefficient. I get now that it was a good idea, I will change it back.
Thank you for you advice.

This article has been dead for over six months. Start a new discussion instead.