随机文件生成器循环不能生成正确数量的文件
Random File Generator Loop does not generate correct amount of files
我使用ofstream
生成随机文件,其中存储有文本。然而,似乎应该指定生成多少.txt
文件的fileNum
变量不起作用。生成的.txt
文件数量与实际指定的数量有较大差异。有时是4(或3或2),有时是正确的。我不太确定哪里不对,我对c++很陌生
string genRandStr(int len, int seed) {
// Add a seed, so a different random number is generated each time
srand(time(seed));
char alphaNum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
int strlen = sizeof(alphaNum) - 1;
string randStr = "";
for (int i = 0; i < len; i++) {
randStr += alphaNum[rand() % strlen];
}
return randStr;
}
//main function
int main()
{
int fileNum;
cout << "FILEWARS - SAFE VERSION - USE WITH CARE" << endl;
cout << "Made By: David Yue" << endl;
cout << "Enter the amount of files you wish to create: ";
cin >> fileNum;
if (cin.fail()) {
cout << "Value must be an integer." << endl;
}
if (fileNum >= 30) {
cout << "SAFE VERSION RESTRICTION: File Amount may not exceed 30" << endl;
main();
} else {
ofstream file1;
stringstream fileName;
for (int i = 0; i <= fileNum; i++) {
fileName << genRandStr(6, time(i) ) << ".txt";
file1.open(fileName.str());;
for (int i = 0; i < 10; i++) {
file1 << genRandStr(100, time(i)) << "n";
}
file1.close();
file1.clear();
fileName.str("");
fileName.clear();
Sleep(1000);
}
system("pause");
}
}
它正在生成相同的文件名,因此在某些时候它不会创建新文件,而是覆盖旧文件。我假设您希望每个文件的不同/唯一名称,因此我建议您选择任何基本名称(例如MyFile)并在其旁边添加+
和count
。将计数初始化为1,然后在每次迭代/新文件时增加count
。结果应该得到所有文件的唯一名称,例如:file1
, file2
, file3
..等
或者,如果您仍然需要使用Random Generator,那么srand(time(seed));
(无论您如何选择seed
的值)应该在整个程序执行期间只调用一次,并且在每次调用时而不是。因此,使用Null
而不是seed
,并在代码的顶部全局声明srand(time(Null));
。初始化它仅一次将使您能够自由地使用rand();
,并保证每次调用都得到不同的号码。但是要注意% strlen
,因为字符串可能仍然得到相同的sizeof
。
相关文章:
- 为什么头文件不能相互包含?
- 为什么我可以从C++文件中读取 int 值,但不能浮点?
- 为什么我不能从同一目录中的另一个文件中 #include 我的类?
- CStdioFile 不能处理大于 2GB 的文件?
- 不能在其他文件中包含结构
- 有没有办法关闭文件? fclose 不能很好地工作
- 我的项目中某些仅标头文件不能包含使用 CMake 和 Vscode 的"SFML/Graphics.hpp"
- OpenGL不能在核心配置文件中使用glVertexAttrib进行绘制
- 为什么这个文件不能在 gcc 中编译?它在 VS 中工作正常
- Ffmpeg头文件不能在windows中编译
- 为什么文件不能在Apache的CGI中创建
- 用Visual Studio 11编译的可执行文件有什么特别之处,导致这些可执行文件不能在Windows XP上执行?
- 文件不能正确读取c++ ifstream
- 使文件不能链接c++,即使有.o文件
- c++文件不能使用特定的#include进行编译,而其他文件都可以
- 为什么对象 (.obj) 文件不能跨平台移动?
- c++可执行文件不能在windows7-64位不兼容的环境下运行
- 为什么我的#include文件不能编译
- 包含文件不能被识别,即使它们在正确的目录中
- 为什么这个生成文件不能正确编译?