我正在为我的 C++ 决赛编写一个基于战舰棋盘游戏的程序,我目前正在处理的问题是如何管理用户帐户。我必须允许用户每次玩游戏时都使用同一个帐户并跟踪他们的赢/输记录。我可以将数据写入文件,但我需要在玩家重新登录时将其读回,然后对其进行排序以找到他们的用户名。我被困在这部分。
这是我正在使用的文件,它读取为用户名,wins,losses:
Rocky 0 0
Bob 0 0
dave 0 0
Jerry 0 0
Bert 0 0
Ernie 0 0
Marcus 0 0
编辑:这是我要重复很多次的输出
-858993460
-858993460
-858993460
-858993460
-858993460
-858993460
UserData 是一个结构
//begin create/find account function
userData createAccount(userData ud){
//local variables
int playerOption;
//creates object to open files
ifstream infile;
//creates object to open files
ofstream outfile;
do {
cout << "Do you have an existing account?" << endl;
cout << "" << endl;
cout << "Enter 1 for yes or 2 for no:" << endl;
cin >> playerOption;
}
while (playerOption >= 3 || playerOption <= 0);
if (playerOption == 1){
cout << "Enter user name:" << endl;
cin >> ud.name;
//opens file in read mode
infile.open("userData.dat");
//tests to make sure the file is open
if (!infile){
cout << "File open failure!";
}
//creates array of user data
userData userDataArray [SIZE];
//reads data from file into array until end of file
int i=0;
while(i<SIZE){
infile >> userDataArray[i].name;
infile >> userDataArray[i].wins;
infile >> userDataArray[i].losses;
i++;
}
///test output
int j=0;
while (j<SIZE){
cout << userDataArray[j].name << endl;
cout << userDataArray[j].wins << endl;
cout << userDataArray[j].losses << endl;
j++;
}
//end test output
//closes file
infile.close();
}
else if(playerOption == 2){
cout << "Enter user name:" << endl;
cin >> ud.name;
ud.wins = 0;
ud.losses = 0;
//opens file in write mode
outfile.open("userData.dat",ios::app);
//tests to make sure the file is open
if (!outfile){
cout << "File open failure!";
}
//writes userData struct to file
outfile << ud.name << " " << ud.wins << " " << ud.losses << endl;
//closes file
outfile.close();
}
return ud;
//end create/find account function
}