C language implements random roll caller

Directory

1. Program description

2. Program function

3. The detailed implementation process of the function

Student structure declaration and definition

menu function

File reading and saving functions

query function

roll call function

rand function

roll call function implementation

Function to reset roll call times to zero

font color change function

4. Operation effect

5. Source code sharing


1. Program description

Only use C language to make a roll call program that runs on the command line. When the program is running, the specified txt file is used as the “class” roster. After running, the interface will display Random name The process of strong>, from fast to slow, gradually freezes on a certain name, saves it in a file, and the program ends.

2. Program function

  • Save and read as file
  • Display the roll call of all students
  • Query the roll call of a single classmate
  • Start multiple roll calls
  • Start individual roll call
  • Save roll call
  • Reset the roll call to zero
  • Font color changes

3. Detailed function implementation process

Student structure declaration and definition

The “class roster” records the information of a classmate. In the random roll call program, we need to define a structure to save the information of each classmate. Here, we need the name of the classmate, the number of roll calls and the classmate number, so that a structure like the following can be defined:

#define TOTAL 15 //Number of students

struct Student
{
    char name[30]; //student name
    int num; //student number
    int frequency; //Number of roll calls
} stu[TOTAL]; //Student information array of the whole class

The number of the class is variable, here we define a macro definition TOTAL to represent the number of the class, and then use the structure array to store the information of all students.

After defining the structure, we need to start building the framework of the whole program, and then we can write a menu (menu) function, which is convenient for us to use the program and test a single function:

//menu function
void menu()
{
    printf("********************************************\ n");
    printf("********************************************\ n");
    printf("**********Welcome to the class random roll call program********\\
");
    printf("***** input a : display the roll call of all students *****\\
");
    printf("***** input b: check the roll call status of a single classmate *****\\
");
    printf("***** input c: start a single name roll *****\\
");
    printf("***** input d : start calling multiple names *****\\
");
    printf("***** input e : save point name *****\\
");
    printf("***** input f: reset the count to zero *****\\
");
    printf("***** enter q : exit *****\\
");
    printf("********************************************\ n");
    printf("********************************************\ n");
}

File read and save function

After completing the implementation of the menu function, you can implement a single function function. Before the function of displaying the roll call of all classmates and querying the roll call of a single classmate is realized, are we missing something? Is it missing file reading and saving? Otherwise, how do you know the information of the “class” students? So we first write out the function function of reading and saving the txt file:

//Read file function
void readFile()
{
    FILE * fp = fopen("studentname.txt", "rb");
    if (fp == NULL)
    {
        printf("Failed to open the file\\
");
        exit(1);
    }
    else
    {
        for (int i = 0; i < TOTAL; i ++ )
        {
            fscanf(fp, "%d %s %d\\
", & amp;stu[i].num, stu[i].name, & amp;stu[i].frequency);
        }
    }
    fclose(fp);
}

//save file function
void saveFile()
{
    FILE* fp = fopen("studentname.txt", "wb");
    if (fp == NULL)
    {
        printf("\\
Failed to write file\\
");
        return;
    }
    else
    {
        for (int i = 0; i < TOTAL; i ++ )
        {
            fprintf(fp, "%d %s %d\\
", stu[i].num, stu[i].name, stu[i].frequency);
        }
    }
    fclose(fp);
    printf("\\
Saved successfully!\\
");
    printf("\\
");
}

The content of file operations is used here. Readers who are not very familiar with this can check out my blog:

Introduction to C Language – File Operations_sakura0908’s blog – CSDN blog, which contains more detailed explanations of file operation functions, and it is better to understand the above functions.

query function

After reading the “class” file, we can get all the student information, and then we can query the status of all students and the roll call of a single student. These two functions are very easy to implement:

//Query the roll call information of all students
void all_print()
{
    //Display the roll call of all students
    printf("\\
 roll call situation\\
");
    for (int i = 0; i < TOTAL; i ++ )
    {
        printf("%-8d\t%-8s\t was named %d times\\
", stu[i].num, stu[i].name, stu[i].frequency);
    }
    printf("\\
");
}

//Query the roll call information of a single student
void single_print(int num)
{
    for (int i = 0; i < TOTAL; i ++ )
    {
        if (stu[i].num == num)
        {
            printf("%-8d\t%-8s\t was named %d times\\
", stu[i].num, stu[i].name, stu[i].frequency);
            printf("\\
");
            break;
        }
    }
}

Querying the situation of all classmates can be realized directly by using the for loop to traverse and print the entire structure array; querying the roll call of a single classmate is a little more complicated. Pass in the number of the classmate to be queried, and after traversing the structure array, compare the structure in the Student ID returns the subscript of the corresponding structure array.

name function

The roll call function is the core function of this random roll caller. Before implementing this function, let’s first understand the rand function, because the rand function is used in the roll call function. If you don’t know how to use this function, some readers will appear Unexpected error running results,

rand function

The rand function is a function used to generate a random number in C language.

rand function limit: There is a macro #define RAND_MAX 0x7fff in the stdlib.h header file
rand generates a random number of 0-0x7fff, that is, a number maximum is 32767

rand function header file:
#include <stdlib.h>

rand function prototype:
int rand(void);

The rand() function will check whether srand(seed) has been called before each call, and whether a value has been set for the seed. If so, it will automatically call srand(seed) once to initialize its initial value; if it has not been Call srand (seed), then the system will automatically assign the initial value to the seed, that is, srand (1) will automatically call it once

srand function: The srand function is the initialization function of the random number generator

srand function header file:
#include <stdlib.h>

srand function prototype:
void srand(unsigned int seed);

This function needs to provide a seed, such as srand(1), initialize the seed with 1. When rand() generates random numbers, if you use srand(seed) to sow seeds, Once the seeds are the same, the generated random numbers will be the same. Of course, in many cases, the random numbers generated by rand() are deliberately randomized, and time is used as the seed srand(time(NULL)), so that the time of running the program must be different each time, and the generated random numbers must be different.
We often use the system time to initialize, use the time function to obtain the system time, the obtained value is a timestamp, that is, the number of seconds from 13:00 on May 15, 2023 to the current time, and then convert the obtained time_t type data into ( unsigned int), and then passed to the srand function

srand((unsigned int)time(NULL));//When we use rand and srand, we mainly use this initialization method! !

If you still feel that the time interval is too small, you can multiply an appropriate integer after (unsigned)time(0) or (unsigned)time(NULL).
Passing NULL for the parameter of time means that the time_t data obtained through the parameter does not need to be obtained. The prototype of the time function is as follows

time function header file:
#include <time.h>

Prototype of time function:
time_t time(time_t *tloc);//time_t type is defined as a long integer

There is another way to initialize the seed as follows, using the pid of the process as the seed value seed, in the same program, the value of such a seed is the same

srand((unsigned int)getpid());

The use of the rand function, if you want to indicate that a number starts from 0 to the maximum value, for example, if you want to generate a random number between 0-99, then the usage is as follows:

int num = rand() % 100;

If you want to generate a number starting from 1 to the maximum value, for example, if you want to generate a random number between 1-100, then the usage is as follows:

int num = rand() % 100 + 1;

Need to pay attention to the difference between + 1 and not + 1 at the end, the minimum value of + 1 is 1, and the minimum value of not + 1 is 0

Roll function realization

To achieve the function of name blinking during random roll call, you need to use the escape character \r. Its function is to move the cursor to the beginning of the line without changing the line. If the information is output at this time, the information will be The original content will be overwritten. Repeat this process, properly handle the problem of different lengths of a line, and you can keep flashing different names in the same message. The roll call function for a single classmate is as follows:

//Single student roll call function
void Named()
{
    int id = -1;
    int t = 300;
    //Configure the "seed" coefficient generated by the random number for rand() to obtain the current system time
    srand((unsigned)time(NULL));

    printf("\\
Start roll call\\
");
    //Cycle 15 random points function
    for (int i = 0; i < 15; i ++ )
    {
        for (int j = 0; j < TOTAL; j ++ )
        {
            // Find the remainder to obtain the array subscript corresponding to the name and its corresponding memory address
            id = rand() % 15;
            //Implement the function of name blinking
            printf("\r \r");
            printf("%s", stu[id].name);
            fflush(stdout);
        }
        //Slowly increase the blinking time
        Sleep(t);
        t + = 60;
    }
    printf("\\
The lucky one is: %s\\
", stu[id].name);

    //Increase the number of roll calls for students drawn
    stu[id].frequency += 1;
    printf("\\
");
}

The function value of the roll call of multiple students needs to be slightly modified in the case of a single student roll call (adding the number of roll call students). The upgraded version of the roll call function is:

//Student roll call function
void Named(int num)
{
    int id = -1;
    int t = 300;
    //Configure the "seed" coefficient generated by the random number for rand() to obtain the current system time
    srand((unsigned)time(NULL));

    printf("\\
Start roll call\\
");
    //Cycle 15 random points function
    for (int k = 0; k < num; k ++ )
    {
        for (int i = 0; i < 15; i ++ )
        {
            for (int j = 0; j < TOTAL; j ++ )
            {
                // Find the remainder to obtain the array subscript corresponding to the name and its corresponding memory address
                id = rand() % 15;
                //Implement the function of name blinking
                printf("\r \r");
                printf("%s", stu[id].name);
                fflush(stdout);
            }
            //Slowly increase the blinking time
            Sleep(t);
            t + = 60;
        }
        printf("\\
The lucky one is: %s\\
", stu[id].name);
        //Increase the number of roll calls for students drawn
        stu[id].frequency += 1;
    }
    printf("\\
");
}

Return to zero function of roll call times

The function of this function, as the name suggests, is to reset the number of roll calls of students to zero, and the implementation steps are also very simple. It can be realized by traversing the entire array of student information structures and reassigning the number of roll calls in each student’s structure to 0. :

//The function of zeroing the number of roll calls
void to_Zero()
{
    for (int i = 0; i < TOTAL; i ++ )
    {
        stu[i].frequency = 0;
    }
    printf("\\
Return to zero\\
");
    printf("\\
");
}

Font color change function

0=black 8=gray
1=blue 9=light blue
2=green 10=light green
3=blue 11=light green
4=red 12=light red
5=purple 13=lavender
6=yellow 14=light yellow
7=white 15=bright white

int color_num = 0;

// font color change function
void color(int x)
{
    if (x >= 0 & & x <= 15)
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), x);
    else//other white
        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7);
}

//Prefix ++ operator has higher priority than modulo operator
color( + + color_num % 16);

If you have any questions about the operator priority above, you can check the operator priority introduction in this blog:

Introduction to C Language – Operators – sakura0908’s Blog – CSDN Blog

4. Running effect

Only some screenshots of running effects are provided here

5. Source code sharing

The function function is almost written above, and the main function of the program is attached at the end. Interested readers can copy it down and run this interesting program by themselves:

int main()
{
    int num = 0;
    char c = '\0';

    while (1)
    {
        menu();
        readFile();
        while ((c = getchar()) != 'q')
        {
            color( + + color_num % 16);
            printf("Please enter the function you want to choose:");
            c = getchar();
            switch (c)
            {
                case 'a':
                    color( + + color_num % 16);
                    all_print();
                    break;
                case 'b':
                    color( + + color_num % 16);
                    printf("Please enter the student number of the student you want to query:");
                    scanf("%d", &num);
                    single_print(num);
                    break;
                case 'c':
                    color( + + color_num % 16);
                    Named(1);
                    break;
                case 'd':
                    color( + + color_num % 16);
                    printf("Please enter the number of people you want to roll:");
                    scanf("%d", &num);
                    Named(num);
                    break;
                case 'e':
                    color( + + color_num % 16);
                    saveFile();
                    break;
                case 'f'://reset the number of roll calls to zero
                    color( + + color_num % 16);
                    to_Zero();
                    break;
                case 'q':
                    printf("\\
Welcome to use the random roll caller next time!\\
");
                    exit(0);
            }
        }
    }
    return 0;
}