排序和写入文件日期
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;
}
这是我上面的代码,我不确定还能做什么来对日期进行排序。我已经为此工作了一段时间,但无法正确处理。我需要帮助,最好是解决我问题的代码。
基本上,日期的类型是"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)
相关文章:
- 如何使用 AWS C++ 开发工具包在给定的开始和结束日期范围内列出 S3 中的文件
- 解析.msg文件的标头流中的日期
- 是否可以在特定日期后没有运行可执行文件
- 如何按创建日期对文件进行排序
- "日期":'class'类型重新定义:错误(日历.cpp文件错误)
- 如何在当前日期/时间之后命名我创建的文本文件
- C++ 显示在 txt 文件中找到的唯一日期及其相关价格
- 排序和写入文件日期
- 将文件名的文件另存为当前时间日期
- 无法将日期写入文件
- 由触发器调用的 MS SQL XP 更改 C++ 文件日期戳,以允许刷新表单应用程序 vb.net
- 从文件中读取大量数据并以有效的方式解析日期.如何提高海量数据的性能
- 使用 C/C++ 中的二叉搜索在日志文件中搜索日期时间
- 如何获取C++文件的编译日期和时间
- 日志文件中的日期使用 ofstream
- 使用C++中的日期和时间命名日志文件
- 将文件的上次修改日期修改为字符串 c++
- 在windows 7中使用windows.h更改C++中的文件创建日期
- Qt资源系统中文件的最后修改日期
- 以格式化的方式打开一个具有日期的文件,并获取该日期进行比较