Hello. I have a problem with the code below. In the view records menu, after I input something in add records, instead of storing all the inputs that I have done in add records, it overwrites the old input that I have done to it. Can someone help me fix the code and explain what is the problem with it? Thanks.
#include <iostream>
#include <fstream>
#include <string>
constexpr size_t maxrow {5};
std::string gb_nickname[maxrow] {};
unsigned gb_age[maxrow] {};
int gb_score1[maxrow] {};
int gb_score2[maxrow] {};
void addrecord() {
std::string nickname;
unsigned age {};
int score1 {};
int score2 {};
//system("clear");
std::cin.ignore();
std::cout << "Enter nickname: ";
std::getline(std::cin, nickname);
std::cout << "Age: ";
std::cin >> age;
std::cout << "Enter Score 1: ";
std::cin >> score1;
std::cout << "Enter Score 2: ";
std::cin >> score2;
for (size_t x = 0; x < maxrow; ++x)
if (gb_nickname[x].empty()) {
gb_nickname[x] = nickname;
gb_age[x] = age;
gb_score1[x] = score1;
gb_score2[x] = score2;
break;
}
std::ofstream myfile("players.txt", std::ios::app);
if (!myfile)
std::cout << "Cannot open file\n";
else {
myfile << " Nickname: " << nickname << '\n' << " Age: " << age << '\n' << " Score 1: " << score1 << '\n' << " Score 2 " << score2 << '\n';
std::cout << "\nFile was saved successfully!\n";
}
std::cout << "Press any key followed by <CR> to continue... ";
std::cin.ignore();
std::cin.get();
}
void viewrecord() {
//char menu {};
size_t counter {};
//system("clear"); //clear the screen
std::cout << "\n\t\t\t\t\t\t\b\b\b\b\b\b\b\b RECORDS LIST\n";
for (size_t x = 0; x < maxrow; ++x)
if (!gb_nickname[x].empty()) {
++counter;
std::cout << counter << "." << " Nickname: " << gb_nickname[x] << '\n' << " Age: " << gb_age[x] << '\n' << " Score 1: " << gb_score1[x] << '\n' << " Score 2: " << gb_score2[x] << '\n';
}
if (counter == 0)
std::cout << " No records found.\n";
//cout << "\v\v\v\t\t\t\t\t\t\b\b\b\b\b\b\b\b\b\bPress 'M' to go to Main Menu: ";
//cin >> menu;
}
int main() {
unsigned num {};
do {
//system("clear");
std::cout << " MAIN MENU\n";
std::cout << "1. Add record\n";
std::cout << "2. View players records\n";
std::cout << "3. Exit\n";
std::cout << "\nPick a number: ";
std::cin >> num;
switch (num) {
case 1:
addrecord();
break;
case 2:
viewrecord();
break;
case 3:
break;
default:
std::cout << "Invalid number\n";
break;
}
} while (num != 3);
}
Note that although the players.txt file accumulates the entered data, the program doesn't first read the file to obtain already entered data. If you want option 2) to display all entered data, then you'll need a function to read the file and update the arrays. If you want to do this, then the format of the file isn't the best for reading and parsing.