如何用随机数填充文件

How to populate a file with random numbers?

本文关键字:文件 填充 随机数 何用      更新时间:2023-10-16

因此,基本上我正在尝试"填充"一个具有10^3的文件完全随机数,因此我稍后可以将它们添加到二进制搜索树中。这是我到目前为止工作的填充功能:

void populateFile(BinarySearchTree b) {
    int random_integer;
    srand( time( NULL ) );
    std::ofstream myfile;
    string line;
    myfile.open ("output.txt");
    myfile << "Writing this to a file: ";
    for(int index=0; index<1000; index++)
    {
        random_integer = (rand()%1000)+1;
        cout << random_integer << endl;
        myfile << random_integer;
    }
    myfile.close();
    int value;
    ifstream file ("output.txt");
    if (file.is_open())
    {
        while ( getline (file,line) )
        {
            value = std::stoi(line);
            b.insert(value);
        }
        myfile.close();
    }
    else cout << "Unable to open file";
}

但是我似乎无法写入文件,我只能在控制台上看到数字,然后程序崩溃。

我的第二个关注点是:我想将这些相同的数字添加到二进制搜索树中。我已经有一个课程和DD功能,但是我不知道如何继续。然后,我希望能够随机从BST中删除它们。

我已经写了一个删除函数。这怎么可能?任何想法都将不胜感激。P.S:我是C 的新手,如果我的问题对您来说很愚蠢,我感到很抱歉。

我认为您问题的解决方案在于@praetorian的评论:

您可能想要myfile << random_integer << 'n';。否则stoi将投掷out_of_range,这可能是崩溃的原因。

我对您的功能有一些通用建议。

  1. 将您的功能分为两个

    - 一个用于文件
    的写作 - 一个用于从文件中读取并填充bst。

  2. 不要在功能中使用文件的硬编码名称或全局变量。使他们对功能进行辩论。

  3. 始终检查IO操作的状态。处理失败。

  4. main或驱动程序函数中播种随机数生成器。如果您调用多次生成随机数的函数,则无需再次播种随机发生器。

void populateFile(int count,
                  std::string const& file)
{
    std::ofstream myfile(file);
    if (!myfile )
    {
       // Deal with error.
       return;
    }
    for(int index=0; index<count; index++)
    {
        random_integer = (rand()%1000)+1;
        myfile << random_integer << "n";
    }
}
void readFileAndBuildBST(std::string const& file,
                         BinarySearchTree& b)
{
    std::ifstream myfile(file);
    if (!myfile )
    {
       // Deal with error.
       return;
    }
    int number;
    while ( myfile >> number )
    {
       b.insert(number);
    }
}
void driver()
{
   // Seed the random number generator.
   srand( time( NULL ) );
   // Populate the file
   std::string file("output.txt");
   populateFile(1000, file);
   // Read the data from the file and flesh out the BST.
   BinarySearchTree b;
   readFileAndBuildBST(file, b);
}

将功能分为两个,您可以一次测试一个函数。如果一个函数中存在问题,则可以调试问题并在处理另一个功能之前对其进行修复。

更改

cout << random_integer << endl;
myfile << random_integer;

to:

myfile << random_integer << endl;

在旁注上,如果仅在程序的一生中需要数据,则可能需要使用缓冲区,甚至直接将数字添加到您的二进制搜索树中。