[英]Sort a txt file with int and string in ascending order of priority in C++
[英]Parse (split) a txt file with a string and int in c++
我是一名學生,也是這個網站的新手。 我想將我的 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;
}
為highscore::Player
做一個>>
重載。
在>>
重載
std::getline
從輸入 stream 中讀取一行。std::istringstream
。std::getline
將istringstream
中的:
讀入本地string name;
.std::getline
將該行的 rest 讀入string
。std::stoi
將string
轉換為int
並存儲到本地int score;
. 確保提供pos
參數。pos
參數與string
的長度進行比較,確保整個string
都已轉換。name
和score
存儲到調用者傳遞的highscore::Player
中。 否則,使用setstate
在輸入 stream 上設置故障位現在閱讀代碼應該很簡單,例如
int scorecount = 0;
while (myfile >> HighscoreListe[scorecount])
{
scorecount++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.