如何用随机数填充文件
How to populate a file with random numbers?
因此,基本上我正在尝试"填充"一个具有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
,这可能是崩溃的原因。
我对您的功能有一些通用建议。
-
将您的功能分为两个
- 一个用于文件
的写作 - 一个用于从文件中读取并填充bst。 -
不要在功能中使用文件的硬编码名称或全局变量。使他们对功能进行辩论。
-
始终检查IO操作的状态。处理失败。
-
在
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;
在旁注上,如果仅在程序的一生中需要数据,则可能需要使用缓冲区,甚至直接将数字添加到您的二进制搜索树中。
相关文章:
- 用二进制文件填充结构
- 如何使用文件填充结构(下面附有的代码)?
- 用空格填充 2D 数组(从文件输入)
- 如何从文件中填充类中的结构
- 如何创建一个新的二进制文件并用常量值填充它?
- 如何将目录中的文件属性填充到结构向量中?
- 如何使用文件填充数组并将其与用户输入C 进行比较
- 有没有办法在不使用 set_buff() 的情况下从文件中读取并填充消息增益
- 使用.txt文件填充 STL 列表不起作用
- 从文件填充 2D 数组
- 在 Windows 上从文件填充多维矩阵很慢
- 如何创建一个ifstream对象的数组,以及如何使用编号的文本文件填充该数组
- 从文件填充对象的向量
- 从顺序文件填充二维数组
- 用驱动器上的目录和文件填充树视图
- 在检查现有元素时,从文件填充并行数组时出现问题
- 用于从文件填充类的词法分析器/解析器的语法规则
- 冒泡排序在结构化列表中,由csv文件填充
- 对通过外部文件填充的数组进行不正确的排序和/或搜索
- 从文件填充结构