c++ - 如何获取用户输入并按变量排序?

标签 c++ arrays sorting variables user-input

我需要通过十个条目获取用户的姓名、出生日期、出生地点、性别和年龄。然后我需要按年龄从小到大对所有内容进行排序。这是我对此的处理方法:

#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/

相关文章:

ios - 如何按日期排序获取请求而不需要时间 - Swift 3

c++ - 如何在运行时检查 void* 是否为 IUnknown*?

c++ - 获取可变参数模板的除最后一个参数之外的所有参数

c++ - Lambda 捕获列表和复制

c++ - Nuclide C++ 简单降压配置

Python:根据项目和外部键对列表进行排序

python - 添加许多具有重叠索引和列的 pandas 数据框

java - 移动字符串数组中的元素,直到所选字母位于索引 0 处

php - 如何根据php中的日期列对mysql结果数组进行降序排序?

java - TreeMap高低键整数排序