简体   繁体   中英

How to populate an array with a user-defined number of random values

Working on an exercise and I think I'm pretty close to getting it right. The prompt asks for me to have the user say how many random numbers they want generated, and then to generate that many random numbers. For simplicity I'm having the random numbers be 0-1000. We're practicing using files too, so we want this written to a file.

#include <iostream>
#include <fstream>
#include <ctime>

int main()
    {
    int userinput,i, N, rdnum[N];
    std::ofstream ofs;

    std::cout << "How many random numbers do you want to generate?\n";
    std::cin >> N;

    srand(time(0));
    rdnum[N] = rand() % 1001;

    ofs.open("rand_numbers.txt");

    if (!ofs)
    {
        std::cout << "Open error\n";
        exit(0);
    }

    else if (ofs.good())
    {
        for (i = 0; i < N; i++)
        {
            std::cout << "Random numbers: " << rdnum[i] << std::endl;
            ofs << rdnum[i] << std::endl;
        }
    }
}

Thanks!

int userinput,i, N, rdnum[N];

Here, you declare an integer N leaving it with an indeterminate value.

You also declare an array of length N . The behaviour of using an indeterminate value like this is undefined.

Besides, N is not a runtime constant value, so using it as the size of an automatic array is ill-formed.

To create an array of runtime size, you have to use dynamic storage. The simplest way to create a dynamic array is to use std::vector . Note that for this simple program, no array is necessary since you could simply output the random number directly in the loop where it is generated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM