我需要获得用户的姓名,出生日期,出生地,性别和年龄,以及十个条目。然后我需要按年龄排序,从最小到最老。这是我的方法:
#include <iostream>
#include <cstdlib>
#include <sstream>
using namespace std;
int main ()
{
int age;
string name, dob, pof, gender;
array a, b, c, d, e, f, g, h , i, j;
cout << "Please enter your name, date of birth, place of birth, gender, and age, separated by a space.\nFor example, John 1/15/1994 Maine Male 20: ";
cin >> name >> dob >> pof >> gender >> age;
cout << "Your name is " << name << ". Your birthday is " << dob << ". Your place of birth is " << pof << ". You are a " << gender << ". You are " << age << " old.";
ofstream outfile("output.txt");
outfile<<name<<endl;
outfile.close();
return 0;
}
我想将它们存储到一个文件中,然后按年龄按每行排序。由于10个条目将有10行,然后打印出来。这是一个很好的方法吗?还是有更好的方法来解决这个问题?
编辑:这就是我所拥有的:enter image description here
答案 0 :(得分:1)
我建议使用结构(类)并在结构中提供输入,输出和比较的方法:
struct Person
{
unsigned int age; // Unsigned because ages are not negative.
std::string first_name;
//...
friend std::istream& operator>>(std::istream& input, Person& p);
bool operator<(const Person& other) const;
bool operator==(const Person& other) const;
};
std::istream& operator>>(std::istream& input, Person& p)
{
input >> p.age;
input >> p.first_name;
//...
return input;
}
通过将输入方法放入结构中,您可以执行以下操作:
Person p;
std::vector<Person> directory;
while (datafile >> p)
{
directory.push_back(p);
}
// Sorting the directory
std::sort(directory.begin(), directory.end());