Introduction to C + + - Speech Contest process management system

Reference link

  1. https://www.bilibili.com/video/BV1et411b73Z?p=264

Speech contest process management system

Program requirements of speech contest

Competition rules

  1. The school held a speech contest, in which 12 people participated. There are two rounds in the competition. The first round is the knockout and the second round is the final
  2. Each contestant has a corresponding number, such as 10001-10012
  3. Competition mode: group competition, with 6 people in each group
  4. The first round is divided into two groups. The whole group will make speeches after drawing lots according to the contestant's number
  5. The ten judges will score each contestant respectively, remove the highest score and the lowest score, and the average score is the score of the contestants in this round
  6. After the group speech, the last three players in the group will be eliminated, and the top three will be promoted to the next round of competition
  7. The second round is the final, and the top three win
  8. After each round of competition, the information of the promoted players needs to be displayed

Program function

  1. Start the speech contest: complete the process of the whole contest. You need to give the user a prompt at each stage of the contest. The user can press any key to continue to the next stage
  2. View previous records: view the top three results of previous competitions. Each competition will be recorded in a file, which is saved with the. csv suffix
  3. Clear the game record: clear the data in the file
  4. Exit the competition program: you can exit the current program

Create management class

Function description

  1. Provide menu interface and user interaction
  2. Control the speech contest process
  3. Read write interaction with files

create a file

Create speechManager.h and speechManager.cpp files under the folder of header file and source file respectively

class SpeechManager
{
public:
    // Constructor
    SpeechManager();
    // Destructor
    ~SpeechManager();
};
#include "speechManager.h"

// Constructor
SpeechManager::SpeechManager()
{

}
// Destructor
SpeechManager::~SpeechManager()
{
    
}

Menu function

Add member function

Add the member function void show in the management class speechManager.h_ Menu();

// Menu function
void show_Menu();

Menu function realization

Implement show in the management class speechManager.cpp_ Menu() function

// Menu function
void SpeechManager::show_Menu()
{
    cout << "*****************************************" << endl;
    cout << "***********  Welcome to the speech contest  ************" << endl;
    cout << "***********  1.Start the speech contest  **************" << endl;
    cout << "***********  2.View previous records  **************" << endl;
    cout << "***********  3.Clear game records  **************" << endl;
    cout << "***********  0.Exit the game program  **************" << endl;
    cout << endl;
}

Test menu function

Test the menu function in the speech contest process management system. cpp

#include <iostream>
using namespace std;
#include "speechManager.h"

int main()
{
    // Create management class
    SpeechManager sm;

    sm.show_Menu();

    system("pause");
    return 0;
}

Exit function

Provide functional interface

Branch selection is provided in the main function, and each function interface is provided

int main()
{
    // Create management class
    SpeechManager sm;

    int choice = 0; // Options used to store users

    while (true)
    {
        sm.show_Menu();

        cout << "Please enter your choice:" << endl;
        cin >> choice; // Accept user's options

        switch (choice)
        {
            case 1: // Start the game
                break;
            case 2: // View records
                break;
            case 3: // Clear record
                break;
            case 0: // Exit the system
                break;
            default:
                system("cls"); // Clear screen
                break;
        }
    }

    system("pause");
    return 0;
}

Realize exit function

Provide the member function void exitSystem() to exit the system in speechManager.h;
Specific function implementation is provided in speechManager.cpp

void SpeechManager::exitSystem()
{
    cout << "Welcome to use next time" << endl;
    system("pause");
    exit(0);
}

Speech contest function

functional analysis

Analysis of competition process:
Draw lots – > start the speech contest – > display the results of the first round – >
Draw lots – > start speech contest – > display top three results – > Save scores

Create player class

The attributes in the player category include: player name and score
Create the speaker.h file in the header file and add code:

class Speaker
{
public:
    string m_Name; // full name
    double m_Score[2]; // There are two rounds of scores at most
};

match

Add member properties

Add properties in speechManager.h

// 12 competitors
vector<int> v1;

// 6 persons promoted in the first round
vector<int> v2;

//3 winners
vector<int> vVictory;

// Storage number and corresponding specific information
map<int, Speaker> m_Speaker;

// Record the number of rounds
int m_Index;
Initialize properties

Provide the member function void initSpeech() to start the competition in speechManager.h;

//Initialize properties
void initSpeech();

Implement void initSpeech() in speechManager.cpp;

void SpeechManager::initSpeech()
{
    // The container is guaranteed to be empty
    this->v1.clear();
    this->v2.clear();
    this->vVictory.clear();
    this->m_Speaker.clear();
    //Initialize rounds
    this->m_Index = 1;
}

void initSpeech() is called in the SpeechManager constructor;

SpeechManager::SpeechManager()
{
    // Initialize properties
    this->initSpeech();
}
Create player

In speechManager.h, provide the member function void createspike() to start the competition;

// Initialize and create 12 players
void createSpeaker();

Implement void createspike() in speechManager.cpp;

void SpeechManager::createSpeaker()
{
    string nameSeed = "ABCDEFGHIJKL";
    for (int i = 0; i < nameSeed.size(); i++)
    {
        string name = "player";
        name += nameSeed[i];

        Speaker sp;
        sp.m_Name = name;
        for (int j = 0; j < 2; i++)
        {
            sp.m_Score[i] = 0;
        }

        // Number of 12 contestants
        this->v1.push_pack(i + 10001);

        // The contestant number and the corresponding contestant are stored in the map container
        this->m_Speaker.insert(make_pair(i + 10001, sp));
    }
}

void createSpeaker() is called in the constructor of class SpeechManager;

SpeechManager::SpeechManager()
{
    // Initialize properties
    this->initSpeech();

    // Create player
    this->createSpeaker();
}
Start adding competition member functions

Provide the member function void startSpeech() to start the competition in speechManager.h;
The function is to control the process of the game

// Start competition - competition process control
void startSpeech();

In speechManager.cpp, write the empty implementation of startSpeech first

void SpeechManager::startSpeech()
{
    // First round
    // 1. Draw lots

    // 2. Competition

    // 3. Display promotion results

    // Second round
    // 1. Draw lots

    // 2. Competition

    // 3. Display final results

    // 4. Save scores

}
draw

In speechManager.h, provide the member function void speechDraw();

// draw
void speechDraw();

Implement the member function void speechDraw() in speechManager.cpp;

void SpeechManager::speechDraw()
{
    cout << "The first << " << this->m_Index << " >> The players in the round are drawing lots" << endl;
    cout << "----------------------" << endl;
    cout << "After drawing lots, the speech sequence is as follows:" << endl;
    if (this->m_Index == 1)
    {
        random_shuffle(v1.begin(), v1.end());
        for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++)
        {
            cout << *it << " ";
        }
        cout << endl;
    }
    else
    {
        random_shuffle(v2.begin(), v2.end());
        for (vector<int>::iterator it = v2.begin(); it != v2.end(); it++)
        {
            cout << *it << " ";
        }
        cout << endl;
    }
    cout << "--------------------" << endl;
    system("pause");
    cout << endl;
}

In the function of startSpeech game flow control, the lottery function is called.

// 1. Draw lots
speechDraw();

In the main function, the branch 1 option calls the interface to start the race.

case 1: // Start the game
    sm.startSpeech();
    break;
Start the game

In speechManager.h, provide the member function void speechContest();

// match
void speechContest();

Implement the member function void speechContest() in speechManager.cpp;

void SpeechManager::speechContest()
{
    cout << "--------------The first" << this->m_Index << "The first round of official competition begins: --------------" << endl;

    multimap<double, int, greater<double>> groupScore; // Temporary container for saving key score and value contestant number

    int num = 0; // Record the number of personnel, 6 for 1 group

    vector<int> v_Src; // Competition personnel container
    if (this->m_Index == 1)
    {
        v_Src = v1;
    }
    else
    {
        v_Src = v2;
    }

    // Traverse all parameters
    for (vector<int>::iterator it = v_Src.begin(); it != v_Src.end(); it++)
    {
        num++;

        // Judges score
        deque<double> d;
        for (int i = 0; i < 10; i++)
        {
            double score = (rand() % 401 + 600) / 10.f; // 600~1000
            d.push_back(score);
        }

        sort(d.begin(), d.end(), greater<double>());
        d.pop_front();
        d.pop_back();

        double sum = accumulate(d.begin(), d.end(), 0.0f);
        double avg = sum / (double)d.size();

        // Average score per person
        this->m_Speaker[*it].m_Score[this->m_Index - 1] = avg;

        // In a group of 6 people, keep it in a temporary container
        groupScore.insert(make_pair(avg, *it));
        if (num % 6 == 0)
        {
            cout << "The first" << num / 6 << "Group competition ranking: " << endl;
            for (multimap<double, int, greater<double>>::iterator it = groupScore.begin(); it != groupScore.end(); it++)
            {
                cout << "No.:" << it->second << "full name:" << this->m_Speaker[it->second].m_Name << " Achievement:" << this->m_Speaker[it->second].m_Score[this->m_Index - 1] << endl;
            }

            int count = 0;
            // Top three
            for (multimap<double, int, greater<double>>::iterator it = groupScore.begin(); it != groupScore.end() && count < 3; it++, count++)
            {
                if (this->m_Index == 1)
                {
                    v2.push_back((*it).second);
                }
                else
                {
                    vVictory.push_back((*it).second);
                }
            }

            groupScore.clear();

            cout << endl;
        }
    }
    cout << "-------------- The first" << this->m_Index << "The round is over ---------------" << endl;
    system("pause");
}
Show game scores

Provide the member function void showScore() to display scores in speechManager.h;

// Show game results
void showScore();

Implement the member function void showScore() in speechManager.cpp;

void SpeechManager::showScore()
{
    cout << "-------------- The first" << this->m_Index << "The information of the contestants in the round is as follows:--------------------" << endl;
    vector<int> v;
    if (this->m_Index == 1)
    {
        v = v2;
    }
    else
    {
        v = vVictory;
    }

    for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
    {
        cout << "Contestant number:" << *it << "full name:" << m_Speaker[*it].m_Name << " score:" << m_Speaker[*it].m_Score[this->m_Index - 1] << endl;
    }
    cout << endl;

    system("pause");
    system("cls");
    this->show_Menu();
}

In the function of startSpeech game flow control, the function of displaying the game score is called.

Second round

In the function of startSpeech competition process control, add the process of the second round

void SpeechManager::startSpeech()
{
    // First round
    // 1. Draw lots
    this->speechDraw();

    // 2. Competition
    this->speechContest();

    // 3. Display promotion results
    this->showScore();

    // Second round
    this->m_Index++;
    // 1. Draw lots
    this->speechDraw();

    // 2. Competition
    this->speechContest();
    
    // 3. Display final results
    this->showScore();

    // 4. Save scores

}

Save score

Add the record saving member function void saveRecord() in speechManager.h;

// Keep records
void saveRecord();

Implement the member function void saveRecord() in speechManager.cpp;

void SpeechManager::saveRecord()
{
    ofstream ofs;
    ofs.open("speech.csv", ios::out | ios::app); // Open file as output

    // Write everyone data to file
    for (vector<int>::iterator it = vVictory.begin(); it != vVictory.end(); it++)
    {
        ofs << *it << ","
            << m_Speaker[*it].m_Score[1] << ",";
    }
    ofs << endl;

    // Close file
    ofs.close();

    cout << "The record has been saved" << endl;

    this->fileIsEmpty = false;
}

In the startSpeech game process control function, the last call saves the record score function.

// 4. Save scores
this->saveRecord();

cout << "The competition is over!" << endl;
system("pause");
system("cls");

View records

Read record score

Add the member function void loadRecord() for reading records in speechManager.h;
Add the flag bool fileIsEmpty to judge whether the file is empty;
Add the capacity of previous records map < int, vector > m_ Record;

Where M_ The key in the record represents the boundary, and the value records the specific information

// Read record
void loadRecord();

// Flag for empty file
bool fileIsEmpty;

// Previous records
map<int, vector<string>> m_Record;

Implement the member function void in speechManager.cpp_ loadRecord();

void SpeechManager::loadRecord()
{
    ifstream ifs("speech.csv", ios:in); // Input stream object read file

    if (!ifs.is_open())
    {
        this->fileIsEmpty = true;
        cout << "File does not exist!" << endl;
        ifs.close();
        return;
    }

    char ch;
    ifs >> ch;
    if (ifs.eof())
    {
        cout << "The file is empty!" << endl;
        this->fileIsEmpty = true;
        ifs.close();
        return;
    }

    // File is not empty
    this->fileIsEmpty = false;

    ifs.putback(ch); // Put the read single character back

    string data;
    int index = 0;
    while (ifs >> data)
    {
        vector<string> v;
        int pos = -1;
        int start = 0;

        while (true)
        {
            pos = data.find(",", start); // Find ',' from 0
            if (pos == -1)
            {
                break; // break return not found
            }
            string tmp = data.substr(start, pos - start); //Found, split
            v.push_back(tmp);
            start = pos + 1;
        }

        this->m_Record.insert(make_pair(index, v));
        index++;
    }

    ifs.close();
}

Call the previous record function in the SpeechManager constructor.

// Get previous records
this->loadRecord();

View record function

Add the member function void showRecord() to speechManager.h to save records;

// Show previous scores
void showRecord();

Implement the member function void showRecord() in speechManager.cpp;

void SpeechManager::showRecord()
{
    if (this->fileIsEmpty)
    {
        cout << "The file is empty or does not exist!" << endl;
    }
    for (int i = 0; i < this->m_Record.size(); i++)
    {
        cout << "The first" << i + 1 << "session " <<
            "Champion No.:" << this->m_Record[i][0] << " score:" << this->m_Record[i][1] << " " <<
            "Runner up number: " << this->m_Record[i][2] << " score: " << this->m_Record[i][3] << " " <<
            "Runner up No: " << this->m_Record[i][4] << " score: " << this->m_Record[i][5] << endl;
    }
    system("pause");
    system("cls");
}

Clear record

Implementation of situation recording function

Add the member function void clearRecord() to save records in speechManager.h;

// Clear record
void clearRecord();

Implement the member function void clearRecord() in speechManager.cpp;

void SpeechManager::clearRecord()
{
    cout << "Confirm emptying?" << endl;
    cout << "1,confirm" << endl;
    cout << "2,return" << endl;

    int select = 0;
    cin >> select;

    if (select == 1)
    {
        // Open the mode ios::trunc. If it exists, delete the file and re create it
        ofstream ofs("speech.csv", ios:trunc);
        ofs.close();

        //Initialize properties
        this->initSpeech();

        //Create player
        this->createSpeaker();

        //Get previous records
        this->loadRecord();

        cout << "Empty successfully!" << endl;
    }

    system("pause");
    system("cls");
}

In the main function branch 3, calling the interface to empty the match record.

case 3: // Clear record
    sm.clearRecord();
    break;

Tags: C++ STL map vector

Posted on Sun, 19 Sep 2021 04:12:07 -0400 by crazydip