0
我有一个以特定方式组织的视频游戏角色列表。 我希望能够仅从名单中取出他们的名字并按字母顺序排序。按字母顺序排序C++
名单由格式化:
Last Name, First Name, Game, Relase Date, Score, Developer
名单是:
Snake, Solid, Metal Gear Solid, 9/3/1998, 94, Konami
Drake, Nathan, Uncharted, 11/19/2007, 90, Naughty Dog
Guy, Doom, Doom, 5/13/1993, 95, iD
我想输出是:
Drake, Nathan
Guy, Doom
Snake, Solid
我可以在只打印有名字他们在文本文件中的顺序。我如何比较姓氏,然后打印出全名?
这是到目前为止我的代码:
#include <fstream>
#include <iostream>
#include <string>
#include <time.h>
#include <cstdlib>
#include <sstream>
using namespace std;
ifstream inFile;
class Characher{
private:
string first;
string last;
public:
Character(){};
void getLast(){
if(inFile.is_open()){
getline(inFile, last,',');
} else {
cout<<"Hmm.."<<endl;
}
}
void getFirst(){
if(inFile.is_open()){
getline(inFile, first,',');
} else {
cout<<"No First Name here..."<<endl;
}
}
void printLast(){
cout<<last<<",";
}
void printFirst(){
cout<<first<<endl;
}
};
class Dev{
private:
string Developer;
public:
Dev(){};//null constructor
void printDeveloper(){
cout<<"Developer: "<<Developer<<endl;
}
void getDeveloper(){
if(inFile.is_open()){
getline(inFile, Developer);
} else {
cout<<"Nothing here..."<<endl;
}
}
};
class Game{
private:
string game;
public:
Game(){};
void getGameName(){
if(inFile.is_open()){
getline(inFile, game,',');
} else{
cout<<"What game was they frum?"<<endl;
}
}
void printGame(){
cout<<"Game: "<<game;
}
};
class RelDate_And_Score{
private:
string ReleaseDate;
string Score;
public:
RelDate_And_Score(){};
void GetRelDate(){
if(inFile.is_open()){
getline(inFile, ReleaseDate, ',');
} else{
cout<<"Could not find Release Date"<<endl;}
}
void getScore(){
if(inFile.is_open()){
getline(inFile, Score, ',');
} else{
cout<<"Could not find Score"<<endl;}
}
void PrintDate(){
cout<<"Release Date: "<<ReleaseDate<<" | ";}
void PrintScore(){
cout<<"Score: "<<Score<<endl;}
};
int main(){
inFile.open("Games.dat");
Dev d;
Characher c;
RelDate_And_Score r;
Game g;
for (int i=0; i<3; i++)
{
c.getLast();
c.getFirst();
g.getGameName();
r.GetRelDate();
r.getScore();
d.getDeveloper();
c.printLast();
c.printFirst();
}
return 0;
}
在std ::排序你的意思['标准:: sort'(HTTP: //en.cppreference.com/w/cpp/algorithm/sort)?在你的对象上定义'operator <'或者写一个'Compare'函数来比较它们。 – tadman
您无法更改文件中的顺序,因此您需要在内存中创建副本:创建地图,将每一行添加到地图并将名称作为关键字。在地图上的循环会将它们显示为排序 – Lanting
您的设计具有不同的角色,游戏,日期等类别,每个类打开并访问全局文件对象,比所需的更复杂,并且可能无法正常工作,因为这些类会通过读取同一行来干扰。每行有一个类实例会更容易,字符,游戏等字符串成员,将这些类的实例放入向量中(不要在循环中使用数字3,保持灵活性),然后在矢量上使用'std :: sort'。 –