长时间阅读后的分词错误 #包括 #包括 #包括 结构文件数据 { 字符文件名[100]; 整数大小; 煤焦类型; 长时间戳; }; 作废打印(struct fileData*myFile); 内部主(空) { struct fileData*tuse=malloc(sizeof(tuse)); 字符温度[100]={0}; printf(“输入类型:”); getchar(); scanf(“%c”,使用->类型); getchar(); printf(“输入文件名:”); fgets(温度,100,标准温度); strcpy(使用->文件名,临时文件); printf(“输入访问时间:”); scanf(“%lf”,使用->时间戳); printf(“输入大小:”); 扫描量(“%d”,使用->大小); 印刷(使用); 免费(使用); } 作废打印(结构文件数据*myFile) { printf(“文件名:%s-大小:%d-类型:[%c]-已访问@%ld\n”,myFile->Filename,myFile->Size,myFile->Type,myFile->timestamp); }
好的,下面是程序应该做的:长时间阅读后的分词错误 #包括 #包括 #包括 结构文件数据 { 字符文件名[100]; 整数大小; 煤焦类型; 长时间戳; }; 作废打印(struct fileData*myFile); 内部主(空) { struct fileData*tuse=malloc(sizeof(tuse)); 字符温度[100]={0}; printf(“输入类型:”); getchar(); scanf(“%c”,使用->类型); getchar(); printf(“输入文件名:”); fgets(温度,100,标准温度); strcpy(使用->文件名,临时文件); printf(“输入访问时间:”); scanf(“%lf”,使用->时间戳); printf(“输入大小:”); 扫描量(“%d”,使用->大小); 印刷(使用); 免费(使用); } 作废打印(结构文件数据*myFile) { printf(“文件名:%s-大小:%d-类型:[%c]-已访问@%ld\n”,myFile->Filename,myFile->Size,myFile->Type,myFile->timestamp); },c,pointers,struct,scanf,fgets,C,Pointers,Struct,Scanf,Fgets,好的,下面是程序应该做的: 为文件的数据创建结构(必须在main中使用指针) 结构的malloc内存,并提示/读入有关结构的数据 编写一个函数,用于打印该数据 所以。。。以上是我的代码,我有几个问题: 你可能会注意到我在里面有一些getchar(),原因是因为无论什么原因,当我运行时。/a.out它总是跳过我猜测的第一个scanf,因为当我按enter键时,它会卡在stdin中,并将其解析为scanf,所以将getchar()的工作放入。。但有没有办法避免这种情况同时发生?这在我的其他程序中从未
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct fileData
{
char fileName[100];
int size;
char type;
long timestamp;
};
void print(struct fileData *myFile);
int main(void)
{
struct fileData *toUse = malloc(sizeof(toUse));
char temp[100] = {0};
printf("Enter the type:");
getchar();
scanf("%c", toUse->type);
getchar();
printf("Enter the filename:");
fgets(temp, 100, stdin);
strcpy(toUse->fileName, temp);
printf("Enter the access time:");
scanf("%lf", toUse->timestamp);
printf("Enter the size:");
scanf("%d", toUse->size);
print(toUse);
free(toUse);
}
void print(struct fileData *myFile)
{
printf("Filename: %s - Size: %d - Type: [%c] - Accessed @ %ld\n", myFile->fileName, myFile->size, myFile->type, myFile->timestamp);
}
或者:
struct fileData *toUse = malloc(sizeof *toUse);
// ^^^^^^
您需要传入变量的地址:
struct fileData *toUse = malloc(sizeof(struct fileData));
filename是一个字符数组,所以对(filename,,,,)的引用实际上就是地址。其他值是标量,而不是数组。因为您没有分配足够的空间
SizeOf(使用)
=32位机器上的地址大小=4字节,但显然您的结构大小超过100字节
因此,您需要分配结构文件日期的大小
更改:
scanf("%lf", &(toUse->timestamp));
printf("Enter the size:");
scanf("%d", &(toUse->size));
致:
为避免编译器警告不兼容的指针类型:
struct fileData *toUse = malloc(sizeof(struct fileData));
请尝试scanf(“%c\n”,…),以便scanf等待返回字符
fgets(使用->文件名,100,标准输入);可以工作,使用->文件名=“测试”;不要因为“Test”是指向“Test”字符串的指针,而使用->fileName是一个缓冲区,您可以直接在其中设置
%lf是一种长浮点格式。在扫描中尝试%ld。然后,您需要为scanf提供一个要写入的地址,使用scanf(“%ld”,&tuse->timestamp)
大小相同:scanf(“%d”,使用->大小);应为scanf(“%d”,使用->大小(&U))
其他人发现的malloc大小也是一个需要解决的问题。
struct fileData *toUse = malloc(sizeof(struct fileData));
struct fileData *toUse = (struct fileData *) malloc(sizeof(struct fileData));