johnny880
johnny880

Reputation: 33

How to get user input and sort by variable?

I need to get the user's name, date of birth, place of birth, gender, and age with ten entries. Then I need to sort everything by age, youngest to oldest. Here is my approach on this:

#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;
}

I want to store them into a file and then sort it by each line by the age. There will be 10 lines because of the 10 entries and then print it out. Is this a good way of doing this or is there a better way of going about this?

EDIT: Here is what I have: enter image description here

Upvotes: 0

Views: 565

Answers (1)

Thomas Matthews
Thomas Matthews

Reputation: 57729

I recommend using a structure (class) and providing methods in the structure for input, output and comparison:

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;
}

By placing the input method into the structure you can do things like this:

Person p;
std::vector<Person> directory;
while (datafile >> p)
{
  directory.push_back(p);
}

// Sorting the directory
std::sort(directory.begin(), directory.end());

Upvotes: 1

Related Questions