【问题标题】:Problems while creating files with random file names while using std::ofstream in C++在 C++ 中使用 std::ofstream 创建具有随机文件名的文件时出现问题
【发布时间】:2013-12-02 01:47:50
【问题描述】:

我有这段代码,我正在努力工作(不正确)现在它会创建一个大文件,但我希望它生成一系列随机标题的文件。

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

【问题讨论】:

  • 如果你使用的是c++03,那么你必须使用std::ofstream o(file.c_str()),因为ofstream在c++11之前没有使用string的构造函数,只有@987654327 @.
  • 在我的 gcc 版本 4.6.3 上编译得很好。

标签: c++ file random compiler-errors ofstream


【解决方案1】:
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)] );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-07
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    相关资源
    最近更新 更多