我的任务是制作一个程序,该程序读取.txt文件并在控制台中显示某些情况下60岁以上人群的信息,而在第二种情况下让我按姓氏查找一个人。文本文件包含其在列表中的位置,出生日期,国家/地区,姓名,姓氏的信息。第一种有效,但是在第二种情况下我很难获得结果。
int Search_in_File(char *fname, char *str) {
FILE *fp;
int line_num = 1;
int find_result = 0;
char temp[40];
if((fp = fopen(fname, "r")) == NULL) {
return(-1);
}
while(fgets(temp, 40, fp) != NULL) {
if((strstr(temp, str)) != NULL) {
printf("\n%s\n", temp);
find_result++;
}
line_num++;
}
if(find_result == 0) {
printf("\nSorry, couldn't find a match.\n");
}
//Close the file if still open.
if(fp) {
fclose(fp);
}
return(0);
}
getchar();
switch(sel){
case 1:
printf("Find person\n");
printf("Enter surname to find: ");
fgets(cmp, 40, stdin);
err = Search_in_File(fname, cmp);
if(err < 0)
{
return err;
}
break;
case 2: //here should be the option of printing people who are older than 60
}while(sel!=4);
return 0;
}
这样做的正确和最佳方法是什么?考虑到我必须计算不包括year年的年龄,或者仅计算年份本身(不包括月和日)。
例如,如果我有4个人:
1 11/10/1987 country1 John Doe
2 12/08/1950 country2 Mary Solley
3 23/02/1988 country3 Kieth Owell
4 29/12/1954 country4 Bob Stevens
而且我选择了显示60岁以上人群的选项,它应该输出:
2 12/08/1950 country2 Mary Solley
4 29/12/1954 country4 Bob Stevens
最佳答案
有
char line[] = "4 11/10/1987 country1 John Doe";
您可以使用以下命令将日期,月份和年份提取为字符串
char day[3] = "";
char month[3] = "";
char year[5] = "";
strncpy(day, line+2, 2);
strncpy(month, line+5, 2);
strncpy(year, line+8, 4);
当心ID。当它达到10(或100或1000)时,您需要调整起始索引。