将随机整数写入文本文件,且不重复。

3

我是一个编程和Stack Overflow的新手。所以我一直在构建一个简单的数据库,以供自己享受和练习我的知识。它会将用户的用户名、密码和分配给用户的用户ID记录到文本文件中,您还可以查看用户的信息。

我的主要问题是,我希望程序为用户分配一个随机的ID,例如1-1000(例如1000是最大员工数量)。

当用户注册新的用户名和密码时,这个代码块就被执行。程序会在这部分输出用户名、密码和用户ID。我能够让程序为每个创建的用户输出一个随机数,但我无法使其生成没有重复的数字。

程序应该输出一条消息,如果没有更多的用户ID可用,那么注册过程将不会完成。

我创建了一个打印一堆行以清除屏幕的函数,但所有内容都在底部。如果有其他函数可以使用,我会很高兴知道!

if (passwordCheck == password) {
            const int minEmp = 1, maxEmp = 10;          
            srand(time(0));
            userID = (rand() % (maxEmp - minEmp + 1)) + minEmp;

            ofstream outfile (username + ".txt"); //Creates txt file with user name
            outfile << "User ID: " << userID << endl << //Outputs info to txt file
                "Account Username: "<< username << endl
                << "Account Password: " << password;
            outfile.close();
            clearScreen(); //My function to add lines to clear the screen

            cout << endl << "Your account has been created." << endl
                << endl << "Returning to main menu.";

            clearScreen();
            mainMenu(); //Function to return back to menu

我不明白实际的问题,你想为每个用户生成一个唯一的随机数吗? - Ali Sepehri-Amin
3
我的主要问题是,我希望程序能够为用户分配一个随机的ID,例如从1-1000。这里的问题在哪里?如果你想从该范围内生成唯一的ID,最简单的解决方案是记住/读取所有已使用的ID,并生成一个不在“已使用ID”列表中的ID。你尝试过这个方法吗? - Algirdas Preidžius
5
你应该只调用一次srand函数。为什么不能从1开始分配ID并简单地递增呢? - rustyx
所以你想知道如何确保不会意外地分配相同的数字?Algirdas的建议可能是最简单的,应该可以很好地工作。您还可以尝试像这里一样复杂的操作:https://dev59.com/4nRB5IYBdhLWcg3wLkxM - Kyle A
只要求唯一性,我会使用一个递增的数字。 - Galik
最初生成并存储所有数字1..1000的列表。然后每次随机选择其中一个并将其从列表中删除。 - Bo Persson
2个回答

2
你面临的基本问题是随机数生成不保证唯一性。它甚至不能保证程序运行期间的唯一性(例如,如果你想在多次运行程序期间修改数据库并保持一致性)。因此,你需要一种生成一组唯一ID的方法,删除已经使用过的任何ID(例如,在数据库中表示),然后对剩余的内容进行洗牌。
一种方法可能是:
1. 创建一个包含1000个(或所需数量)唯一ID的列表(例如,使用向量)。这可以通过简单循环或使用适当的生成器调用std :: generate()来完成,该生成器每次调用都会返回不同的值。生成唯一ID的方法需要是一致的(没有随机性)以便第二步能够正常工作。 2. 读取数据库并从列表中删除每个存在于数据库中的ID。 3. 如果剩余列表中没有元素,则不允许添加更多用户。 4. 洗牌列表。在C++11或更高版本中,请使用std :: shuffle()。你需要了解随机数生成。在C++14之前,你可能会使用std :: random_shuffle(),但要记住它使用rand()生成随机值,其质量不确定 - 这就是为什么它在C++14中被弃用(标记为将来从标准中删除)。 5. 每当你需要一个新的唯一值(例如,创建用户)时,从列表中获取最后一个值,将该值从列表中删除,创建用户并将其保存到数据库中。

这正是我一直在寻找的,一个向量。虽然我之前没有听说过它们,但自从得到答案后,我一直在阅读相关资料,并会尽快尝试将其应用到我的程序中。非常感谢! - Johnson Nguyen

1

有一个棘手的问题需要解决:假设你想要随机生成10个值作为排列,然后将它们存储在文件中。

因此,您可以计算如何生成随机索引,然后使用这些索引在值数组上存储数据:

有一天我也遇到了类似的问题,当我开发一款带有图像的纸牌游戏时,每次失败时隐藏的图像会随机跳到某些位置。

#include <iostream>
#include <fstream>
#include <ctime>


int main(){

    srand(time(NULL)); 

    std::ofstream out("data.txt");

    // arrays of data whose values will be stored randomly in a text file.  
    int array[10] = {7, 57, 23, 21, 1,
                    0, 18, 19, 3, 777};

    // array of indexes and initializing it
    int indexes[10];
    for(int i(0); i < 10; i++)
        indexes[i] = rand() % 10;

    // indexes are filled with random values from 0 to 9 but it surely contains duplicates eg:

    // 3, 0, 7, 5, 2, 8, 0, 1, 0, 0


    // Now I use my algorithm to discard duplicates and repeating until I get an array of unique indexes.

    for(int i = 0; i < 10; i++){
        for(int j(0); j < 10; j++){
            if(indexes[i] == indexes[j] && i != j){
                indexes[j] = rand() % 10;
                i = 0;
            }           
        }
    }   

    // check out that the indexes are unique and no duplicates there:

    std::cout << "\n\nThe random indexes: " << std::endl;

    for(int i = 0; i < 10; i++)
        std::cout << indexes[i] << ", ";

    // writing the random values of array using the random indexes array to the file:

    for(int i = 0; i < 10; i++)
        out << array[indexes[i]] << ", ";

    // printing the random values of the array
    std::cout << "\n\nThe random values: " << std::endl;

    for(int i = 0; i < 10; i++)
        std::cout << array[indexes[i]] << ", ";

    out.close();

    std::cout << std::endl << std::endl << std::endl;
    return 0;
}

输出:尝试多次运行程序并查看结果。
//   1
The random indexes:
3, 9, 5, 1, 7, 6, 0, 4, 8, 2,

The random values:
21, 777, 0, 57, 19, 18, 7, 1, 3, 23,

//   2
The random indexes:
5, 8, 0, 1, 3, 9, 4, 2, 6, 7,

The random values:
0, 3, 7, 57, 21, 777, 1, 23, 18, 19,


//   3
The random indexes:
6, 7, 3, 1, 5, 2, 4, 9, 0, 8,

The random values:
18, 19, 21, 57, 0, 23, 1, 777, 7, 3,
  • I offered only a small example so in your case if you want 1000 unique values just look at 0-1000 as an array of unique values so you can use the algorithm above:

    1// initializing
    int randValues[1000];
    for(int i(0); i < 1000; i++)
        randValues[i] = (rand() % 1000) + 1; // because you want to discard 0
    

    now get the unique values:

    for(int i(0); i < 1000; i++){
        for(int j(0); j < 1000; j++){
            if(randValues[i] == randValues[j] && i != j){
                randValues[j] = (rand() % 1000) + 1;
                i = 0; // reset
            }
        }
    }
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接