如何用随机数填充文件?

问题描述 投票:4回答:2

所以基本上,我试图用10 ^ 3个完全随机数“填充”一个文件,因此以后可以将它们添加到Binary搜索树中。这是到目前为止我使用的填充函数:

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中完全删除它们。

我已经编写了删除功能。这怎么可能?任何想法将不胜感激。附注:我对C ++还是陌生的,如果我的问题对您来说听起来很傻,我感到抱歉。

c++ algorithm sorting binary-tree binary-search-tree
2个回答
5
投票

我认为您的问题的解决方案在于@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);
}

将功能分为两部分,您可以一次测试一个功能。如果一个功能有问题,则可以调试该问题并修复,然后再使用其他功能。


0
投票

更改

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

至:

myfile << random_integer << endl;

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

© www.soinside.com 2019 - 2024. All rights reserved.