Search code examples
c++sortingfstream

Sorting and writing to file dates


#include <iostream>     // std::cout
#include <cstdlib>
#include <climits>
#include <algorithm>
#include <cmath>
#include <fstream>

using namespace std;

struct student{
    int ID;           // ID
    string firstname; // first name
    string lastname;  // last name
    int date;         // YYMMDD

    static bool sort_date(student a, student b){
        long data1;
        long data2;
        data1 = a.date;
        data2 = b.date;
        if(data1 < 150000){
            data1 += 20000000;
        }
        else{
            data2 += 19000000;
        }
        if(data2 < 150000){
            data2 += 20000000;
        }
        else{
            data1 += 19000000;
        }
        return data1 < data2;
    }

};

bool is_num(const string &s);
void input_year(student &students);
int length_of_int(int x);

int main(){

    student students[5];

    students[0].date = 000101;
    students[1].date = 951230;
    students[2].date = 570509;
    students[3].date = 120915;
    students[4].date = 020324;

    stable_sort(students, students + 5, student::sort_date);

    ofstream file;
    file.open("sort_date.txt");
    for(int i = 0; i < 5; i++){
        file << students[i].date << endl;
    }

    return 0;
}

void input_year(student &students){
    while(true){
        string input;
        cin >> input;
        if(is_num(input)){
            students.date = atoi(input.c_str());
            if(length_of_int(students.date) != 6){
                cout << "Error, try again." << endl;
            }
            else{
                //
                break;
            }
        }
        else{
            cout << "Error, try again." << endl;
        }
    }
}

bool is_num(const string &s){
    string::const_iterator it = s.begin();
    while(it != s.end() && isdigit(*it)){
        ++it;
    }
    return !s.empty() && it == s.end();
}

int length_of_int(int input){
    int length = 0;
    while(input > 0){
        length++;
        input /= 10;
    }
    return length;
}

This is my code above and I'm not sure what else to do to sort the dates.. I've been working on this for a while and can't get it right. I need help, preferably a code which solves my problem.

Basically, the type of date is "YYMMDD", so in sort_date function, I make those integers in format of "YYYYMMDD" and then sort them and then again become YYMMDD. However, the sorting is somehow wrong.. I tried several times, and when writing a date like "010101" in the file, it removes the first "0", so I am looking for help with those two problems. Any help is appreciated.


Solution

  • If a leading 0 is significant, then you don't have an int, but a string. You can check whether strings are sorted using < just as well as you can ints.

    Also look at your if-else for adding 19 or 20; you check data1 but then modify data2 (and vice versa)....