将rand()结果写入C ++中的文本文件而不重复数字

时间:2014-02-23 17:13:01

标签: c++ random ofstream

在我的程序中的这一点上,我每次编写一个随机数时,数组中该数字的内容被写入文本文件。代码:

#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <time.h>
#include "inFrench.h"

using namespace std;

class student
{
    int m_studentNumber;
public:
    string nameFirst;
    string nameLast;
    string nameFull;
    int getStudentNumber() { return m_studentNumber; }
    void setStudentNumber(int studentNumber) { m_studentNumber = studentNumber; }
};

ostream& operator<<(ostream& os, const student& s)
{
    return os << s.nameFirst << ' ' << s.nameLast;
}

student typeName()
{
    student bar;
    cout << "Type in a student's first name: ";
    cin >> bar.nameFirst;
    cout << "Type in that student's last name: ";
    cin >> bar.nameLast;
    bar.nameFull = bar.nameFirst + " " + bar.nameLast;
    return bar;
}

void displayStudents(student listOfStudents[50], int studentHeadCount)
{
    for (int i = 0; i < studentHeadCount; i++)
    {
        cout << listOfStudents[i].nameFull << endl;
        cout << listOfStudents[i].getStudentNumber() << endl;
        cout << "\n";
    }
}

void generateGroups(int numberOfGroups, int maxStudents, int studentsPerGroup, int remainder, student theStudents[], int studentsBeenAssigned, ofstream studentGroups)
{
    int k;
    numberOfGroups = maxStudents / studentsPerGroup;
    cout << numberOfGroups << endl;
    srand(time(NULL));
    studentGroups.open("studentGroups.txt");
    while (studentsBeenAssigned < maxStudents && studentsBeenAssigned < maxStudents - remainder)
    {
        for (int j = 0; j < maxStudents - remainder; j++)
        {
            k = rand() % maxStudents;
            cout << theStudents[k].nameFull << endl;
            studentGroups << theStudents[k].nameFull << endl;
            studentsBeenAssigned++;
            if (studentsBeenAssigned == studentsPerGroup)
            {
                cout << "\n";
                studentGroups << theStudents[k].nameFull << endl;
                studentsBeenAssigned = 0;
            }
        }
    }
    if (remainder < studentsPerGroup && remainder > 0)
    {
        for (int l = 0; l < remainder; l++)
        {
            cout << theStudents[k].nameFull << endl;
        }   
    }
}

void languageChoices()
{
    cout << "Select your language from the following:\n";
    cout << "a) English\n";
    cout << "b) French\n";
    cout << "\n";
}

void options()
{

    cout << "Select what you want to do:\n";
    cout << "1) Exit application\n";
    cout << "2) Enter a Student\n";
    cout << "3) Display Students\n";
    cout << "4) Display Groups\n";
    cout << "5) Output groups as text file\n";
    cout << "6) Reset number of students in class\n";
    cout << "7) Reset number of students per group\n";
    cout << "\n";
}

int main()
{
    char selectedLanguage;
    languageChoices();
    cin >> selectedLanguage;
    switch (selectedLanguage)
    {
        case 'a':
        {
            student allStudents[50]; // Having 50 students alone is ridiculous!
            bool endProg = 0;
            int maxStudents;
            int studentsPerGroup;
            int optionSelect;
            int studentHeadCount = 0;
            int remainder = 0;
            int numberOfGroups = 0;
            int studentsBeenAssigned = 0;
            ofstream studentGroups;
            cout << "GroupPicker 1.0\n";
            cout << "Note: This version of the program is intended for purposes of education only, " 
            << "specifically for teacher use in a classroom.\n\n";
            cout << "How many students are in the class?\n" << "(Note: You cannot have more than 50 in this program)\n";
            cin >> maxStudents;
            if (maxStudents > 50)
            {
                cerr << "Too many students!\n" << "Exiting program...\n";
                system("PAUSE");
                exit(1);
            }
            if (maxStudents >= 35 && maxStudents <= 50)
            {
                cout << maxStudents << " students? You are a pro!\n";
            }
            cout << "How many students per group?\n";
            cin >> studentsPerGroup;
            if (studentsPerGroup >= maxStudents || studentsPerGroup <= 1)
            {
                cerr << "You're kidding, right?\n" << "Exiting program...\n";
                system("PAUSE");
                exit(1);
            }
            while (endProg == 0) {
                options();
                cin >> optionSelect;
                switch (optionSelect) {
                    case 1:
                        endProg = 1;
                        break;
                    case 2:
                    {
                        if (studentHeadCount == maxStudents)
                        {
                            cerr << "You can't enter more than " << maxStudents << " students\n";
                        }
                        else
                        {
                            allStudents[studentHeadCount] = typeName();
                            allStudents[studentHeadCount].setStudentNumber(studentHeadCount);
                            cout << "Student (" << allStudents[studentHeadCount].nameFull << ") entered.\n";
                            cout << "\n";
                            studentHeadCount++;
                        }
                        break;
                    }
                    case 3:
                        cout << "Current list of students:\n\n";
                        displayStudents(allStudents, studentHeadCount);
                        break;
                    case 4:
                    {
                        if (studentHeadCount < studentsPerGroup || studentHeadCount < maxStudents)
                        {
                            cerr << "Invalid group parameters.\n" << "Returning to main menu...\n\n";
                            break;
                        }
                        else
                        {
                            cout << "Here are the groups:\n\n";
                            studentGroups.open("studentGroups.txt");
                            generateGroups(numberOfGroups, maxStudents, studentsPerGroup, remainder, allStudents, studentsBeenAssigned, studentGroups);
                        }
                        break;
                    }
                    case 5:
                    {
                        cout << "Saving groups to file...\n";
                        studentGroups.close();
                        break;
                    }
                    case 6:
                    {
                        cout << "How many students are in the class?\n" << "(Note: You cannot have more than 50 in this program)\n";
                        cin >> maxStudents;
                        if (maxStudents > 50)
                        {
                            cerr << "Too many students!\n" << "Try again...\n";
                        }
                        if (maxStudents >= 35 && maxStudents <= 50)
                        {
                            cout << maxStudents << " students? You are a pro!\n";
                        }
                        break;
                    }
                    case 7:
                    {
                        cout << "How many students per group?\n";
                        cin >> studentsPerGroup;
                        if (studentsPerGroup >= maxStudents || studentsPerGroup <= 1)
                        {
                            cerr << "You're kidding, right?\n" << "Try again...\n";
                        }
                        break;
                    }
                }
            }
            break;
        }
        case 'b':
        {
            mainInFrench();
        }
    }
}

编译时,我收到以下错误:

error C2248: 'std::basic_ofstream<_Elem,_Traits>::basic_ofstream' : cannot access private member declared in class 'std::basic_ofstream<_Elem,_Traits>'
IntelliSense: "std::basic_ofstream<_Elem, _Traits>::basic_ofstream(const std::basic_ofstream<_Elem, _Traits>::_Myt &_Right) [with _Elem=char, _Traits=std::char_traits<char>]" (declared at line 1034 of "C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include\fstream") is inaccessible

如何解决这些问题(第181行)并确保不会多次生成任何数字?

3 个答案:

答案 0 :(得分:3)

您将按值传递给generateGroups()函数,这会导致复制构造函数调用。标准流无法复制。

至于你问题的第二部分,你不能指望PRNG总是返回唯一数字,更不用说当你用模数限制范围时。您需要编写更多代码,以检查您之前已经生成的数字是否已经生成,或者换句话说,某些学生已被分配。

答案 1 :(得分:3)

std::ofstream无法复制。看起来你需要一个参考:

void generateGroups(int numberOfGroups, int maxStudents, 
                    int studentsPerGroup, int remainder, 
                    student theStudents[], int studentsBeenAssigned, 
                    ofstream& studentGroups)
{//                         ^

答案 2 :(得分:1)

rand()使用的种子在大多数实现中不会重复直到2 ^ 32个循环或更多,但是(种子&gt;&gt; xx)%n将至少每n个循环重复一次,如果n不相对则更频繁地重复对rand()使用的linear congruential generator使用的数字进行素数处理。

您可以创建一个包含n个字节的数组,并使用它们来跟踪是否存在重复。