c++ - 在 C++ 中使用 std::ofstream 创建具有随机文件名的文件时出现问题

标签 c++ file random compiler-errors ofstream

我有这段代码,我正在努力使其发挥作用(不对)现在它创建了一个大文件,但我希望它生成一系列随机命名的文件。

#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());

因为 ofstream 的构造函数需要 const char*


还可以考虑使用以下函数代替 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)] );

关于c++ - 在 C++ 中使用 std::ofstream 创建具有随机文件名的文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20319613/

相关文章:

c++ - 段列表迭代器错误 C++

c++ - 如何在 C++ 中调用可变参数模板构造函数?

c# - 使用 C# 删除超过一个月的文件

java - 当 Java 小程序的多个实例写入服务器上的同一个文件时,如何避免出现错误

r - 使用逆采样从分布函数生成随机变量

c++ - 这是在 C 或 C++ 中生成随机字节数组的好方法吗?

c++ - 为什么用整数文字调用重载的 ambig(long) 和 ambig(unsigned long) 会模棱两可?

c++ - OpenGL For 循环(随机月亮生成)

java - 文本文件号码持有者无法正常工作,如何修复?

sql - 随机选择并不总是返回单行