【发布时间】:2015-03-17 13:16:14
【问题描述】:
这是针对酒店预订系统的,它采用一个 .txt 文件,其中包含 int string string int 行,然后读取该文件并将其放入类型为 room 的数组中......在扫描时它不断给我分段错误.. . 这是上课用的,我不想要一个现成的代码来窃取,但我只是不明白为什么我一直在分段......:/
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int num;
char first[100];
char last[100];
int type;
}room;
int main (int argc, char ** argv){
FILE * myFile;
if(argc !=2)
{
fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
return EXIT_FAILURE;
}
myFile = fopen(argv[1],"r");
if (myFile==NULL){
fprintf(stderr, "no open!!\n");
return EXIT_FAILURE;
}
// counter to add elements to my array
int i = 0;
char c;
//array of room with the 150 rooms in it...
room * rooms = malloc(150 * sizeof(room));
while ((c = getc(myFile)) != EOF ){
fscanf(myFile, "%d", rooms[i].num);
printf("the room num is: %d", rooms[i].num);
fscanf(myFile, "%s", rooms[i].first);
fscanf(myFile, "%s", rooms[i].last);
fscanf(myFile, "%d", rooms[i].type);
i++;
}
fclose(myFile);
}
这是我在我的代码中修复并工作的内容,但它实际上跳过了它从中读取的 .txt 文件中的第一个整数......当它应该是 1 时它只是读取一个零,所以我注意到“ (c = getc(myFile)) != EOF" 是我的问题,它跳过了它应该读取的第一个整数:/
while ((c = getc(myFile)) != EOF ){
fscanf(myFile, "%d", &rooms[i].num);
fscanf(myFile, "%s", rooms[i].first);
fscanf(myFile, "%s", rooms[i].last);
fscanf(myFile, "%d", &rooms[i].type);
printf("the room num is: %d and is occupied by %s %s and it is a %d\n", rooms[i].num, rooms[i].first, rooms[i].last, rooms[i].type);
i++;
}
.txt 文件的第一行如下: 1 卡里奥斯顿 0
【问题讨论】:
-
如果你在 linux 上,
gdb是你的朋友。 :-) -
我在大学集群上运行,我可以使用 gdp 吗?
标签: c