【发布时间】:2021-01-24 22:25:12
【问题描述】:
我是一名学生,并且是本网站的新手。我想将我的 txt 文件与我的高分数据拆分回我的高分列表。 txt 文件存储我的高分,如 name:score 我的解析不起作用,我不知道为什么? 我只想将它拆分为再次命名和评分,然后将其放入我的 HighscoreList 中。
如果您对代码有任何疑问,请询问:)
#include "highscore.h"
highscore::highscore(){
}
struct highscore::Player{
string spielerName;
int score;
};
void highscore::writeHighscore(string name, int score ,int playerNumberx){
Player HighscoreListe[100];
for(int i=0;i<=99;i++){
HighscoreListe[i].score = {0};
}
for(int i=0;i<=99;i++){
HighscoreListe[i].spielerName = "leer";
}
HighscoreListe[playerNumberx].spielerName = name;
HighscoreListe[playerNumberx].score = score;
int i, j,temp;
string temp1;
ifstream myfile("scores.txt");
string line;
//heres the point where i need help!!
if (myfile.is_open()){
int z=0;
while(getline(myfile, line)){
string name1;
string score1;
int d = 20;
while(line[z] != ':'){
name1 += line[z];
z++;
}
z = z+2;
while(line[z] != '\0'){
score1 += line[z];
z++;
}
HighscoreListe[d].spielerName = name;
HighscoreListe[d].score = score;
d++;
}
myfile.close();
}else cout << "Unable to open file" << endl;
for(i = 0; i<100; i++) {
for(j = i+1; j<100; j++)
{
if(HighscoreListe[j].score < HighscoreListe[i].score) {
temp = HighscoreListe[i].score;
temp1 = HighscoreListe[i].spielerName;
HighscoreListe[i].score = HighscoreListe[j].score;
HighscoreListe[i].spielerName = HighscoreListe[j].spielerName;
HighscoreListe[j].score = temp;
HighscoreListe[j].spielerName = temp1;
}
}
}
ofstream myfilex("scores.txt");
if (myfilex.is_open()){
for(int i = 99;i>89;i--){
myfilex << HighscoreListe[i].spielerName << ":" << HighscoreListe[i].score<<endl;
}
myfilex.close();
}
else cout << "Unable to open file" << endl;
}
void highscore::readHighscore(){
string line;
ifstream myfile("scores.txt");
if (myfile.is_open()){
while(getline(myfile, line)){
cout << line << endl;
}
}
else cout << "Unable to open file" << endl;
}
【问题讨论】:
-
显示的代码将数字分数作为文本字符串解析为
score1std::string。显示的代码中没有任何内容将其实际转换为整数值。你需要学习计算机编程的黄金法则:你的计算机总是完全按照你告诉它做的,而不是你想让它做的。您没有告诉您的计算机将字符串解析为整数值并保存,因此您的计算机根本不会这样做。如果您希望它这样做,请确切地告诉您的计算机在这方面您的计算机应该做什么。
标签: c++ arrays string parsing txt