在C++中使用std::ofstream创建具有随机文件名的文件时出现问题
Problems while creating files with random file names while using std::ofstream in C++
我有这段代码,我正在努力让它发挥作用(没有duh right)现在它创建了一个大文件,但我希望它生成一系列随机命名的文件。
#include <iostream>
#include <string>
#include <time.h>
#include <stdlib.h>
#include <fstream>
using namespace std;
string random(int len)
{
string a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string r;
srand(time(NULL));
for(int i = 0; i < len; i++) r.push_back(a.at(size_t(rand() % 62)));
return r;
}
int main(){
std::ofstream o("largefile.txt");
o << random(999) << std::endl;
return 0;
}
我试着添加这个,但我在std::ofstream
中得到了一个关于数据类型的错误
std::string file=random(1);
std::ofstream o(file);
std::string file=random(1);
std::ofstream o(file);
应该是:
std::string file=random(1);
std::ofstream o(file.c_str());
因为CCD_ 2的构造函数期望CCD_。
也可以考虑使用以下函数而不是rand() % 62
:
inline int irand(int min, int max) {
return ((double)rand() / ((double)RAND_MAX + 1.0)) * (max - min + 1) + min;
}
...
srand(time(NULL)); // <-- be careful not to call srand in loop
std::string r;
r.reserve(len); // <-- prevents exhaustive reallocation
for (int i = 0; i < len; i++)
r.push_back( a[irand(0,62)] );
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 从命令行c++发送文本文件名
- 为什么 Serial.println(<char[]>);返回随机字符?
- 字符串-C++后显示的随机字符
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 循环中的随机函数
- 在c++构造函数中使用随机字符串生成器
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 使用std::mt19937从字符串中返回一个随机单词
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- 如何在C++中高效地构造随机骰子
- 在类中使用随机生成器时出现性能问题
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 当Microsoft文档仅包含 C# 示例时,如何查找 C++ 包含文件名
- 将字符随机转换为大写的函数
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 使用GetTemp文件名函数在C++上生成随机文件名
- 在C++中使用std::ofstream创建具有随机文件名的文件时出现问题
- 如何从填充.txt文件名的向量中选取随机元素C++
- 生成一个随机文件名,然后创建文件,在c++中