gpt4 book ai didi

c - 我需要在 c 中读取一个 txt 文件并将日期保存在结构或列表中

转载 作者:太空宇宙 更新时间:2023-11-04 04:33:15 25 4
gpt4 key购买 nike

这是一个文本示例。

ABS 2010-10-11 15:10:10 
PER 2010-10-11 15:10:10
PER 2010-10-11 15:10:10

到目前为止,我可以轻松地将数据放入结构中,而无需像 - 或 : 这样的符号。一些 C 神童可以尝试给我一些关于如何避免这个问题的提示吗?谢谢

代码如下:

#include <stdio.h>
struct Alarm
{
int year;
int month;
int day;
char Type[30];


};
void getStructInfo(struct Alarm theStruct){ //just a function to check if data is stored in the structure
printf("\n");
printf("Type: %s\n\n",theStruct.Type);
printf("Godina:%d\n",theStruct.year );
}
int main(){
struct Alarm a1,a2;
FILE *fp;
fp= fopen("podaci.txt","r");
if(fp == NULL)
{
printf("Error\n");
return 1;

}

while(1){

fscanf(fp,"%s\t%d\t%d\t%d\n",&a1.Type,&a1.year,&a1.month,&a1.day);
printf("%s\t%.4d\t%.2d\t%.2d\n",a1.Type,a1.year,a1.month,a1.day );
printf("Continue reading (y/n)\n");
char ch=getch();
if(ch == 'N' || ch== 'n')
break;

}
fclose(fp);
getStructInfo(a1);
return 0;
}

输出是这样的: ABS 2012 -10 -11

最佳答案

您应该了解 fscanf 的工作原理并使用返回值:

while( fscanf(fp, "%s%d-%u-%u%*s",&a1.Type,&a1.year,&a1.month,&a1.day)==4 )
{
...
}

关于c - 我需要在 c 中读取一个 txt 文件并将日期保存在结构或列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33735374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com