#include <iostream>
#include <cstdlib>

using namespace std;

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

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

int main(){
    student students[100];
    int amount_of_students;
    cin >> amount_of_students;
    for(int i = 0; i < amount_of_students; i++){
        cout << "Enter student's ID" << endl;
        cin >> students[i].ID;
        cout << "Enter student's first name" << endl;
        cin >> students[i].firstname;
        cout << "Enter student's last name" << endl;
        cin >> students[i].lastname;
        cout << "Enter student's date of birth" << endl;
        input_year(students[i]);
    }
    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{
                if()
                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;
}


我有以下代码,我想按DATE对结构的数组(students [100])进行排序,并验证日期的输入。

我现在要做的是验证它是6个字符和一个数字。但是,我也想验证一下它是否是有效日期(01-12个月,01-30天)。

至于这一年,我知道可能存在问题,例如:
501022可能意味着1950年和2050年,但是这有一个特殊情况。

如果年份是50-99,则表示19xx;如果年份是00-14,则表示20xx。

我需要对此进行验证,并需要一种以升序或降序对其进行排序的方法。

最佳答案

要对数组排序,可以使用qsort()例如(http://www.cplusplus.com/reference/cstdlib/qsort/)。它看起来像下面的样子:

函数调用:

qsort (students, amount_of_students, sizeof(student), func_ptr);


比较功能:

typedef int (*compar)(const void*,const void*);
compar func_ptr;

int sort_ascending (const void* student1, cont void* student2)
{
  long value1=student1->date;
  long value2=student2->date;

  if(value1 < 150000)
  { value1 += 20000000;} else { value1 += 19000000;}
  if(value2 <150000)
  { value2 += 20000000;} else { value2 += 19000000;}
  return value1 - value2;
}


对于sort_descending(),您必须切换value1和value2。

编辑:
包括在内


  如果年份是50-99,则表示19xx;如果年份是00-14,则表示20xx。


提示:对于日期,我将使用long而不是int(int具有2或4或8字节,具体取决于系统)

10-07 19:07
查看更多