随机文件生成器循环不能生成正确数量的文件

Random File Generator Loop does not generate correct amount of files

本文关键字:文件 不能 循环 随机文件      更新时间:2023-10-16

我使用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