I am working on an assignment that generates random numbers, writes them to a file, reads them back and displays them on the screen with 10 per row. The problem I am having is when they are displayed back on the screen it always wants to finish the row so it takes the last number and repeats it until there are 10 on that row. If there are an even 10, it will take the last number and make a entire new row of them.
Any suggestions?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iomanip>
using namespace std;
int randomvalue(int &);
void randomwriting (int value1, int &number,int n);
void readingFile ();
int main()
{
int number;
int value1 [number];
int n;
cout << "This program will ask you how many random numbers you \n";
cout << "would like to generate. The numbers will then be written \n";
cout << "to a file, the file closed, then opened and displayed back.\n";
number = randomvalue (number);
randomwriting (value1 [number], number, n);
readingFile ();
system("pause");
return 0;
}
int randomvalue(int &number)
{
cout << "\nPlease enter a number between 50 and 1000: ";
cin >> number;
while (number < 50 || number > 1000)
{
cout << "Your number must be between 50 and 1000\n";
cout << "Please enter another number: ";
cin >> number;
}
return number;
}
void readingFile () {
ifstream readNumberFile;
readNumberFile.open ("Random Numbers.txt");
int x;
int count = 0;
while (readNumberFile >> x) {
cout << setw(5) << x << " ";
count++;
if (count == 10) {
cout << endl;
count = 0;
}
}
if (count != 0) {
cout << endl;
}
readNumberFile.close();
return;
}
when you use it like this it works.
the difference between this and your code is, that you only check after 10 numbers if the file is over.
like: file is over? no. ok, get 10 numbers (the for-loop), ok, printed them, now check if the file is over... when the file is over while you are in the for-loop the x will be left unchanged (thats why it fills up the line with the last digit until the row is complete).