最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Error in Arithmetic Quiz source code in C - Stack Overflow

programmeradmin2浏览0评论

When the 1st player answers ADDITION quiz, everything is okay. But when it is the next players turn, something goes wrong for a single time. When player 2 plays Addition quiz for the first time, its score earned was added to player 1. When player 2 answers it for the second time, the score correctly goes to player 2 already and everything becomes fine. The case of player 2 also applies exactly to the next players - adding their scores to the first player for their first try. This error only happens to ADDITION quiz, and not on the other operations. I haven't seen any other error in the code except this one. I badly needed help. Thank you!

I have tried tweaking the main and all the functions relating to logIn and saveUser functions, but it's just getting worse. I'm expecting for the code to work properly, where the scores are added correctly to the respective players.

THIS IS MY FULL SOURCE CODE:

    #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MAX_USERS 100
#define MAX_NAME_LEN 50
#define FILENAME "Players_Record.txt"

typedef struct {
    char username[MAX_NAME_LEN];
    char password[MAX_NAME_LEN];
    int scores[4]; // Scores for addition, subtraction, multiplication, and 
    division
} User;

User users[MAX_USERS];
int userCount = 0;
User *currentUser = NULL;

void loadUsers();
void saveUsers();
int login();
void signUp();
void sortLeaderboard(int operation);
void displayLeaderboardPerOperation(int operation);
void leaderboardMenu();
void takeQuiz(int operation);
int menu();
void sortLeaderboard(int operation);

int main() {
    loadUsers();
    int loggedIn = 0;

    while (!loggedIn) {
        int choice;
        printf("MAIN MENU\n1. Sign Up\n2. Log In\n3. Exit\n\nEnter choice: ");
        scanf("%d", &choice);
        getchar();

        switch (choice) {
            case 1: 
                system("cls");
                signUp(); 
                loggedIn = 1; 
                system("pause");
                system("cls");
                break;
            case 2: 
                system("cls");
                loggedIn = login(); 
                system("pause");
                system("cls");
                break;
            case 3: 
                printf("Exiting...\n"); 
                exit(0);
            default: 
                printf("Invalid input. Please try again.\n");
                system("pause");
                system("cls");
        }
    }

    while (1) {
        int choice = menu();
        if (choice == 6) {
            printf("Logging Out...\n");
            saveUsers();
            break;
        }
        if (choice == 5) {
            leaderboardMenu();
        } else {
            takeQuiz(choice);
        }
    }
    return 0;
}

int menu() {
    int choice;
    printf("CHOOSE YOUR OPERATION:\n1. Addition\n2. Subtraction\n3. 
        Multiplication\n4. Division\n5. View Leaderboard\n6. Save and Log 
        Out\n\nEnter choice: ");
    scanf("%d", &choice);
    system("cls");
    return choice;
}

void loadUsers() {
    FILE *file = fopen(FILENAME, "r");
    if (!file) return;

    char line[200];  // Buffer for reading lines

    // Skip first two lines (headers)
    fgets(line, sizeof(line), file);
    fgets(line, sizeof(line), file);

    userCount = 0;
    while (fscanf(file, "%s %s %d %d %d %d", users[userCount].username, 
        users[userCount].password, 
                  &users[userCount].scores[0], &users[userCount].scores[1], 
                  &users[userCount].scores[2], &users[userCount].scores[3]) == 
        6) {
        userCount++;
    }
    fclose(file);
    }

    void saveUsers() {
    // Sort users alphabetically by username before saving
    for (int i = 0; i < userCount - 1; i++) {
        for (int j = i + 1; j < userCount; j++) {
            if (strcmp(users[i].username, users[j].username) > 0) {
                User temp = users[i];
                users[i] = users[j];
                users[j] = temp;
            }
        }
    }

    FILE *file = fopen(FILENAME, "w");
    if (!file) return;

    // Write header only once at the top
    fprintf(file, "%-15s %-10s %-10s %-10s %-10s %-10s\n", 
            "Username", "Password", "Addition", "Subtraction", 
        "Multiplication", "Division");
    fprintf(file, "-----------------------------------------------------------        
        ----------------------------------------\n");

    for (int i = 0; i < userCount; i++) {
        fprintf(file, "%-15s %-10s %-10d %-10d %-10d %-10d\n", 
                users[i].username, users[i].password, 
                users[i].scores[0], users[i].scores[1], users[i].scores[2], 
        users[i].scores[3]);
    }
    fclose(file);
}

int login() {
    char username[MAX_NAME_LEN], password[MAX_NAME_LEN];
    printf("Enter username: ");
    scanf("%s", username);
    printf("Enter password: ");
    scanf("%s", password);

    for (int i = 0; i < userCount; i++) {
        if (strcmp(users[i].username, username) == 0 && strcmp(users[i].password, password) == 0) {
            currentUser = &users[i];
            printf("\nLogin successful!\n");
            return 1;
        }
    }
    printf("\nInvalid username or password. Please try again. \n");
    return 0;
}

void signUp() {
    if (userCount >= MAX_USERS) {
        printf("\nUser limit reached!\n");
        return;
    }

    char newUsername[MAX_NAME_LEN], newPassword[MAX_NAME_LEN];

    while (1) {
        int exists = 0;
        printf("Enter new username: ");
        scanf("%s", newUsername);

        // Check if username already exists
        for (int i = 0; i < userCount; i++) {
            if (strcmp(users[i].username, newUsername) == 0) {
                printf("\nUsername already exists! Please choose another.\n\n");
                exists = 1;
                break;
            }
        }
        if (!exists) break;
    }

    printf("Enter new password: ");
    scanf("%s", newPassword);

    // Store the new user
    strcpy(users[userCount].username, newUsername);
    strcpy(users[userCount].password, newPassword);
    for (int i = 0; i < 4; i++) {
        users[userCount].scores[i] = 0;
    }

    currentUser = &users[userCount];
    userCount++;
    saveUsers();
    
    printf("\nSign up SUCCESSFUL!\n\n");
}
void leaderboardMenu() {
    int operation;
    while (1) {
        printf("VIEW LEADERBOARD FOR:\n1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n5. Back to Main Menu\n\nEnter choice: ");
        scanf("%d", &operation);
        system("cls");
        if (operation >= 1 && operation <= 4) {
            displayLeaderboardPerOperation(operation);
            system("pause"); // Pause so the user can view the leaderboard
            system("cls");
        } else if (operation == 5) {
            system("cls");
            return; // Go back to the main menu
        } else {
            printf("Invalid choice. Try again.\n");
            system("pause");
            system("cls");
        }
    }
}

void sortLeaderboard(int operation) {
    for (int i = 0; i < userCount - 1; i++) {
        for (int j = i + 1; j < userCount; j++) {
            if (users[i].scores[operation - 1] < users[j].scores[operation - 1]) {
                // Swap users[i] and users[j]
                User temp = users[i];
                users[i] = users[j];
                users[j] = temp;
            }
        }
    }
}

void displayLeaderboardPerOperation(int operation) {
    char *operations[] = {"Addition", "Subtraction", "Multiplication", "Division"};
    
    // Sort leaderboard before displaying
    sortLeaderboard(operation);
    
    printf("LEADERBOARD - %s\n\n", operations[operation - 1]);
    printf("%-15s %-10s\n", "USERNAME", "SCORE");
    printf("--------------------------\n");

    for (int i = 0; i < userCount; i++) {
        printf("%-15s %-10d\n", users[i].username, users[i].scores[operation - 1]);
    }
}

void takeQuiz(int operation) {
    srand(time(NULL));
    int correct = 0;
    for (int i = 0; i < 10; i++) {
        int a, b, userAns, correctAns;
        char op;
        do {
            a = rand() % 50 + 1;
            b = rand() % 50 + 1;
        } while (operation == 4 && a % b != 0);

        correctAns = (operation == 1) ? a + b : (operation == 2) ? a - b : (operation == 3) ? a * b : a / b;
        op = "+-*/"[operation - 1];

        printf("\n%d %c %d = ", a, op, b);
        scanf("%d", &userAns);

        if (userAns == correctAns) {
            printf("BYUTIPUL!\n");
            correct++;
        } else {
            printf("INCORRECT! The correct answer is %d.\n", correctAns);
        }
    }
    printf("\nYOU GOT %d/10 CORRECT ANSWERS!\n\n\n", correct);
    currentUser->scores[operation - 1] += correct;
    system("pause");
    system("cls");
}

When the 1st player answers ADDITION quiz, everything is okay. But when it is the next players turn, something goes wrong for a single time. When player 2 plays Addition quiz for the first time, its score earned was added to player 1. When player 2 answers it for the second time, the score correctly goes to player 2 already and everything becomes fine. The case of player 2 also applies exactly to the next players - adding their scores to the first player for their first try. This error only happens to ADDITION quiz, and not on the other operations. I haven't seen any other error in the code except this one. I badly needed help. Thank you!

I have tried tweaking the main and all the functions relating to logIn and saveUser functions, but it's just getting worse. I'm expecting for the code to work properly, where the scores are added correctly to the respective players.

THIS IS MY FULL SOURCE CODE:

    #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MAX_USERS 100
#define MAX_NAME_LEN 50
#define FILENAME "Players_Record.txt"

typedef struct {
    char username[MAX_NAME_LEN];
    char password[MAX_NAME_LEN];
    int scores[4]; // Scores for addition, subtraction, multiplication, and 
    division
} User;

User users[MAX_USERS];
int userCount = 0;
User *currentUser = NULL;

void loadUsers();
void saveUsers();
int login();
void signUp();
void sortLeaderboard(int operation);
void displayLeaderboardPerOperation(int operation);
void leaderboardMenu();
void takeQuiz(int operation);
int menu();
void sortLeaderboard(int operation);

int main() {
    loadUsers();
    int loggedIn = 0;

    while (!loggedIn) {
        int choice;
        printf("MAIN MENU\n1. Sign Up\n2. Log In\n3. Exit\n\nEnter choice: ");
        scanf("%d", &choice);
        getchar();

        switch (choice) {
            case 1: 
                system("cls");
                signUp(); 
                loggedIn = 1; 
                system("pause");
                system("cls");
                break;
            case 2: 
                system("cls");
                loggedIn = login(); 
                system("pause");
                system("cls");
                break;
            case 3: 
                printf("Exiting...\n"); 
                exit(0);
            default: 
                printf("Invalid input. Please try again.\n");
                system("pause");
                system("cls");
        }
    }

    while (1) {
        int choice = menu();
        if (choice == 6) {
            printf("Logging Out...\n");
            saveUsers();
            break;
        }
        if (choice == 5) {
            leaderboardMenu();
        } else {
            takeQuiz(choice);
        }
    }
    return 0;
}

int menu() {
    int choice;
    printf("CHOOSE YOUR OPERATION:\n1. Addition\n2. Subtraction\n3. 
        Multiplication\n4. Division\n5. View Leaderboard\n6. Save and Log 
        Out\n\nEnter choice: ");
    scanf("%d", &choice);
    system("cls");
    return choice;
}

void loadUsers() {
    FILE *file = fopen(FILENAME, "r");
    if (!file) return;

    char line[200];  // Buffer for reading lines

    // Skip first two lines (headers)
    fgets(line, sizeof(line), file);
    fgets(line, sizeof(line), file);

    userCount = 0;
    while (fscanf(file, "%s %s %d %d %d %d", users[userCount].username, 
        users[userCount].password, 
                  &users[userCount].scores[0], &users[userCount].scores[1], 
                  &users[userCount].scores[2], &users[userCount].scores[3]) == 
        6) {
        userCount++;
    }
    fclose(file);
    }

    void saveUsers() {
    // Sort users alphabetically by username before saving
    for (int i = 0; i < userCount - 1; i++) {
        for (int j = i + 1; j < userCount; j++) {
            if (strcmp(users[i].username, users[j].username) > 0) {
                User temp = users[i];
                users[i] = users[j];
                users[j] = temp;
            }
        }
    }

    FILE *file = fopen(FILENAME, "w");
    if (!file) return;

    // Write header only once at the top
    fprintf(file, "%-15s %-10s %-10s %-10s %-10s %-10s\n", 
            "Username", "Password", "Addition", "Subtraction", 
        "Multiplication", "Division");
    fprintf(file, "-----------------------------------------------------------        
        ----------------------------------------\n");

    for (int i = 0; i < userCount; i++) {
        fprintf(file, "%-15s %-10s %-10d %-10d %-10d %-10d\n", 
                users[i].username, users[i].password, 
                users[i].scores[0], users[i].scores[1], users[i].scores[2], 
        users[i].scores[3]);
    }
    fclose(file);
}

int login() {
    char username[MAX_NAME_LEN], password[MAX_NAME_LEN];
    printf("Enter username: ");
    scanf("%s", username);
    printf("Enter password: ");
    scanf("%s", password);

    for (int i = 0; i < userCount; i++) {
        if (strcmp(users[i].username, username) == 0 && strcmp(users[i].password, password) == 0) {
            currentUser = &users[i];
            printf("\nLogin successful!\n");
            return 1;
        }
    }
    printf("\nInvalid username or password. Please try again. \n");
    return 0;
}

void signUp() {
    if (userCount >= MAX_USERS) {
        printf("\nUser limit reached!\n");
        return;
    }

    char newUsername[MAX_NAME_LEN], newPassword[MAX_NAME_LEN];

    while (1) {
        int exists = 0;
        printf("Enter new username: ");
        scanf("%s", newUsername);

        // Check if username already exists
        for (int i = 0; i < userCount; i++) {
            if (strcmp(users[i].username, newUsername) == 0) {
                printf("\nUsername already exists! Please choose another.\n\n");
                exists = 1;
                break;
            }
        }
        if (!exists) break;
    }

    printf("Enter new password: ");
    scanf("%s", newPassword);

    // Store the new user
    strcpy(users[userCount].username, newUsername);
    strcpy(users[userCount].password, newPassword);
    for (int i = 0; i < 4; i++) {
        users[userCount].scores[i] = 0;
    }

    currentUser = &users[userCount];
    userCount++;
    saveUsers();
    
    printf("\nSign up SUCCESSFUL!\n\n");
}
void leaderboardMenu() {
    int operation;
    while (1) {
        printf("VIEW LEADERBOARD FOR:\n1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n5. Back to Main Menu\n\nEnter choice: ");
        scanf("%d", &operation);
        system("cls");
        if (operation >= 1 && operation <= 4) {
            displayLeaderboardPerOperation(operation);
            system("pause"); // Pause so the user can view the leaderboard
            system("cls");
        } else if (operation == 5) {
            system("cls");
            return; // Go back to the main menu
        } else {
            printf("Invalid choice. Try again.\n");
            system("pause");
            system("cls");
        }
    }
}

void sortLeaderboard(int operation) {
    for (int i = 0; i < userCount - 1; i++) {
        for (int j = i + 1; j < userCount; j++) {
            if (users[i].scores[operation - 1] < users[j].scores[operation - 1]) {
                // Swap users[i] and users[j]
                User temp = users[i];
                users[i] = users[j];
                users[j] = temp;
            }
        }
    }
}

void displayLeaderboardPerOperation(int operation) {
    char *operations[] = {"Addition", "Subtraction", "Multiplication", "Division"};
    
    // Sort leaderboard before displaying
    sortLeaderboard(operation);
    
    printf("LEADERBOARD - %s\n\n", operations[operation - 1]);
    printf("%-15s %-10s\n", "USERNAME", "SCORE");
    printf("--------------------------\n");

    for (int i = 0; i < userCount; i++) {
        printf("%-15s %-10d\n", users[i].username, users[i].scores[operation - 1]);
    }
}

void takeQuiz(int operation) {
    srand(time(NULL));
    int correct = 0;
    for (int i = 0; i < 10; i++) {
        int a, b, userAns, correctAns;
        char op;
        do {
            a = rand() % 50 + 1;
            b = rand() % 50 + 1;
        } while (operation == 4 && a % b != 0);

        correctAns = (operation == 1) ? a + b : (operation == 2) ? a - b : (operation == 3) ? a * b : a / b;
        op = "+-*/"[operation - 1];

        printf("\n%d %c %d = ", a, op, b);
        scanf("%d", &userAns);

        if (userAns == correctAns) {
            printf("BYUTIPUL!\n");
            correct++;
        } else {
            printf("INCORRECT! The correct answer is %d.\n", correctAns);
        }
    }
    printf("\nYOU GOT %d/10 CORRECT ANSWERS!\n\n\n", correct);
    currentUser->scores[operation - 1] += correct;
    system("pause");
    system("cls");
}
Share Improve this question asked Mar 31 at 7:48 noobnoob 71 silver badge1 bronze badge New contributor noob is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct. 9
  • 2 Your issue is likely due to abuse of globals, making it difficult to analyse the flow. I'm guessing you are not setting currentUser somewhere. You should remove all globals and pass relevant variables into functions instead. Also, you should learn how to use a debugger, it will allow you to to step through code and compare expected variable values to actual ones. – Dominik Kaszewski Commented Mar 31 at 7:55
  • 3 @Aleah, please add input used, output seen, output expected. – chux Commented Mar 31 at 7:59
  • 3 Please try to create a minimal reproducible example to show us, with emphasis on the minimal part. – Some programmer dude Commented Mar 31 at 8:00
  • @chux: In my opinion, it would have made more sense to require this information on the corresponding staging ground post. Instead, you overruled the reviews by two other people requiring major changes (including my review asking for the exact input to be posted), and you approved this post for posting on the main site. – Andreas Wenzel Commented Mar 31 at 23:01
  • Have you tried running your code one line at a time in a debugger while monitoring the control flow and the values of all variables, in order to determine in which line your program stops behaving as intended? If you did not try this, then you may want to read this: What is a debugger and how can it help me diagnose problems? You may also want to read this: How to debug small programs? – Andreas Wenzel Commented Mar 31 at 23:03
 |  Show 4 more comments

1 Answer 1

Reset to default 5

In signup(), you get the current user pointer into currentUser variable, but in saveUsers() you resort your user array thus the current user pointer points to a random user.

发布评论

评论列表(0)

  1. 暂无评论