#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){
if(a.date < 150000){
a.date += 20000000;
}
else{
a.date += 19000000;
}
if(b.date < 150000){
b.date += 20000000;
}
else{
b.date += 19000000;
}
return data1 < data2;
}
};
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;
}
這是我的計劃,我有格式YYMMDD日期,我想將它們轉換成年月日和排序,但在我的算法有問題,我無法找到。轉換YYMMDD到年月日和排序他們
出於某種原因,在文件中的有序輸出看起來是這樣的:
570509
951230
65
8404
120915
我想我的程序,首先,採取日期:
students[0].date = 000101;
students[1].date = 951230;
students[2].date = 570509;
students[3].date = 120915;
students[4].date = 020324;
然後將它們轉換爲年月日和排序他們並以YYYYMMDD格式輸出它們。但輸出不知何故,出於某種原因將101轉換爲65。
正確的輸出應爲:
19570509
19951230
20000101
20020324
20120915
如果您重新閱讀上一個問題的答案,您會看到'000101'是一個八進制數。這與十進制的「65」相同。這似乎是您的代碼的問題之一。 – juanchopanza
@juanchopanza但是,當您將000101轉換爲YYYYMMDD時,它變成了20000101,它仍然是八進制數? – user2943407
但是你不會像那樣轉換它。你把它轉換成'20000065'。而且您不會更改數組中的數據,因此您將以舊格式打印日期。 – juanchopanza