C++ 在C+中使用std::ofstream时,使用随机文件名创建文件时出现问题+;
我有这个代码,我正在努力使工作(没有duh的权利)现在它创建一个单一的大文件,但我希望它生成一系列随机命名的文件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
#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)] );