我需要通过十个条目获取用户的姓名、出生日期、出生地点、性别和年龄。然后我需要按年龄从小到大对所有内容进行排序。这是我对此的处理方法:
#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
最佳答案
我推荐使用一个结构(类)并在结构中提供输入、输出和比较的方法:
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());
关于c++ - 如何获取用户输入并按变量排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33635391/