Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/144.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C+中使用std::ofstream时,使用随机文件名创建文件时出现问题+;_C++_File_Random_Compiler Errors_Ofstream - Fatal编程技术网

C++ 在C+中使用std::ofstream时,使用随机文件名创建文件时出现问题+;

C++ 在C+中使用std::ofstream时,使用随机文件名创建文件时出现问题+;,c++,file,random,compiler-errors,ofstream,C++,File,Random,Compiler Errors,Ofstream,我有这个代码,我正在努力使工作(没有duh的权利)现在它创建一个单一的大文件,但我希望它生成一系列随机命名的文件 #include <iostream> #include <string> #include <time.h> #include <stdlib.h> #include <fstream> using namespace std; string random(int len) { string a = "abc

我有这个代码,我正在努力使工作(没有duh的权利)现在它创建一个单一的大文件,但我希望它生成一系列随机命名的文件

#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::string file=random(1);
std::ofstream o(file.c_str());
因为流的
的构造函数需要
常量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)] );
inline int-irand(int-min,int-max){
返回((双)rand()/((双)rand_MAX+1.0))*(MAX-min+1)+min;
}
...

srand(时间(空));//如果您使用的是c++03,那么您必须执行
std::ofstream o(file.c_str())
,因为
of stream
没有在c++11之前接受
字符串的构造函数,只有
const char*
。在我的gcc版本4.6.3上编译得很好。
std::string file=random(1);
std::ofstream o(file.c_str());
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)] );