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>
#include<iomanip>
#include<fstream>

using namespace std;

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

for(;index<5;)
{
cout<<" Enter number "<< index+1<<" out of 5:";
cin>> pick[index];
if (pick[index]<56)
{
outputfile.open("savednumbers.txt");
outputfile<<pick[index]<<endl;
outputfile.close();
correct=true;
index++;
}
else
{
cout << "You choice is outside of the range.\n Please choose number from 1 to 56.\n";
}
}
}
while( !correct );
cin.clear();
cin.ignore();
cin.get();

}

Recommended Answers

All 2 Replies

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.

Schoil-R-LEA,
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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.