我正在做一项要求我检查学生是否超过 18 岁的作业。我的功能是:
bool Student::isOverEighteen() {
int date[3]; // D/M/Y
char *pdata;
pdata = strtok(Anagrafica::birth, "/"); // Anagrafica is the base class
for (short i = 0; pdata != NULL; i++) {
data[i] = pdata;
pdata = strtok(NULL, "/");
}
time_t t = time(NULL);
tm *locale = localtime(&t);
if (data[0] < locale->tm_mday &&
(data[1] < locale->tm_mon + 1 || data[1] == locale->tm_mon + 1) &&
(locale->tm_year + 1900 - data[3] > 18))
{
return true;
} else {
return false;
}
}
但是,当我显示出生日期时,它会显示日期和学生的教室。例如:25/06/19944A(4A 是教室的名称)
我用来注册学生信息的功能:
Student::Student() {
std::cout << "Name: ";
std::cin.getline(Anagrafica::name, 101);
std::cout << "Surname: ";
std::cin.getline(Anagrafica::surname, 101);
std::cout << "Birth (XX/XX/XXXX): ";
std::cin.getline(Anagrafica::birth, 11);
std::cout << "Classroom: ";
std::cin.getline(Anagrafica::classroom, 101);
}
显示它们的功能:
void Anagrafica::Show() {
std::cout << "\nName:" << this->name;
std::cout << "\nSurname:" << this->surname;
std::cout << "\nBirth:" << this->birth;
std::cout << "\nClassroom: " << this->classroom;
std::cout << std::endl;
}
他们被宣布:
char name[100];
char surname[100];
char birth[10];
char classroom[100];
有什么解决方案可以让它工作吗?
编辑(对于 Nik Bougalis):
这是我现在使用的那个。字符串问题开始是因为我使用的是 c_str;而不是 c_str();
bool Entry::IsOverEighteen() {
int date[3];
date[0] = std::atoi(this->birth.substr(0, 2).c_str()); // Day
date[1] = std::atoi(this->birth.substr(4, 2).c_str()); // Month
date[2] = std::atoi(this->birth.substr(6, 4).c_str()); // Year
time_t t = time(NULL);
tm *local = localtime(&t);
// Perche' sia maggiorenne occorre che:
// Il giorno attuale sia maggiore di quello di nascita
// Il mese attuale sia maggiore o uguale a quello di nascita
// L' anno attuale - l' anno di nascita sia maggiore o uguale 18
if (local->tm_mday > date[0] &&
(local->tm_mon + 1 > date[1] || local->tm_mon + 1 == date[1]) &&
(local->tm_year + 1900 - date[2] > 18 || local->tm_year + 1900 - date[2] == 18))
{
return true;
} else {
return false;
}
}