admin管理员组文章数量:1357707
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
|
Show 4 more comments
1 Answer
Reset to default 5In 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.
本文标签:
版权声明:本文标题:Error in Arithmetic Quiz source code in C - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743961501a2569114.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
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