leaves
leaves

Reputation: 151

I want to create a C++ program to generate random numbers into a file

I'm making a C++ program to generate a million random numbers (I've generated them as just cout output once so I have the processing power) and I want to write them into a file.

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <fstream>
using namespace std;

int main() {
    srand(time(NULL));
    int value;
    ofstream file ("numbers.txt");
    file.open ("numbers.txt", ios::out | ios::app );
    int i = 0;
    while (i < 1000000)
    {
        value = rand(); 
        file << value;
    }
    file.close();
    
}

This is my current code, and I get no errors, but when I run it I see an empty txt file in my file explorer. Can anyone tell me what's the problem here?

I tried it for only 100 numbers, and I got a blank text file

Upvotes: 0

Views: 2218

Answers (2)

Zack
Zack

Reputation: 117

As said by other users in comments, you have an infinite loop: incrementing your loop control variable solves this problem. Then is not necessary to open and close the file explicitly if you use the standard library.

I would add that generally speaking rand() is not the function you may want to use, because it generates pseudo-random numbers, and even if it is ok for your application you may want to give a seed to it, throught the function srand().

If you want more from you program, have a look a this reference page.

Upvotes: 1

Acorn
Acorn

Reputation: 26076

Don't reopen the same file:

...
ofstream file ("numbers.txt");
file.open ("numbers.txt", ios::out | ios::app ); // Remove this line
int i = 0;
...

That will make it work. However, the program won't ever stop, since you forgot to increment i too!

Upvotes: 5

Related Questions