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

时间:2016-07-04 02:35:47

标签: c++

我使用ofstream生成随机文件,其中包含文本。但是,似乎fileNum变量应该指定要生成的.txt个文件的数量不起作用。生成的.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");
    }
}

1 个答案:

答案 0 :(得分:2)

生成相同的文件名,因此在某些时候它不会创建新文件,而是覆盖旧文件。我假设您需要每个文件的不同/唯一名称,因此我建议您选择任何基本名称(示例 MyFile )并在其旁边添加 default: &default adapter: postgresql encoding: unicode host: localhost username: ------- password: ------- pool: 5 development: <<: *default database: myDbName +。将计数初始化为1,然后在每个迭代/新文件上递增count。结果应该为您提供所有文件的唯一名称示例:countfile1file2等等

或者,如果您仍然需要使用随机生成器,那么file3(尽管您是如何选择srand(time(seed));的值)应该在整个程序执行期间仅调用一次并且 not 每次通话。因此,请使用seed代替您的Null,并在代码顶部使用全局seed。只将初始化将使您能够自由使用srand(time(Null));,并保证每次通话都能获得不同的号码。但请注意您的rand();因为字符串可能仍然相同% strlen