排序和写入文件日期

Sorting and writing to file dates

本文关键字:文件 日期 排序      更新时间:2023-10-16
#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;
}

这是我上面的代码,我不确定还能做什么来对日期进行排序。我已经为此工作了一段时间,但无法正确处理。我需要帮助,最好是解决我问题的代码。

基本上,日期的类型是"YYMMDD",所以sort_date函数中,我以"YYYYMMDD"的格式制作这些整数,然后对它们进行排序,然后再次成为 YYMMDD。但是,排序在某种程度上是错误的。我尝试了几次,在文件中写入像"010101"这样的日期时,它会删除第一个"0",所以我正在寻求这两个问题的帮助。任何帮助,不胜感激。

如果前导 0 很重要,那么您没有int,而是string。 您可以检查string是否使用 < 进行排序,就像您可以int s 一样。

还要看看你的if-else添加19或20;你检查data1,然后修改data2(反之亦然)。

在 C 中以 0 开头的数字意味着基数应解释为八进制(基数为 8 而不是 10):文字020324将被解释为十进制数8404

首先将日期转换为 time_t 或 tm,然后使用 datetime 库 (http://en.wikipedia.org/wiki/C_date_and_time_functions)