我正在研究c中需要读取csv数据并将其输入结构的代码。不可否认,我对c ++更熟悉,并且在阅读文件之前没有做太多事情,所以我可能会遗漏一些非常明显的东西。但是当我检查结构数组后,它应该加载数据后,我得到了正确的行数,但除了第二行之外的所有行都是空白的 - 而且由于某种原因,那个只有笑脸......
这是我的代码:
void load_items(){
char file_name[20], buffer[MAX_LINE_LENGTH];
FILE *file;
int i;
printf("Enter the file to load data from: "); //data.csv for here
scanf("%s", file_name);
file=fopen(file_name,"r");
if(file==NULL)
{
printf("Can't open %s\n",file_name);
//exit(EXIT_FAILURE);
}
else {
printf("Congrats! you opened %s as your data source!\n", file_name); //test to make sure opened file
while((fgets(buffer, sizeof(buffer),file)) !=NULL) //while the line isn't blank
{
scanf(buffer,"%s,%s,%d,%d",&places[i].name,&places[i].category,&places[i].x,&places[i].y); //enter data into proper place
printf("|%-23s|%-20s\t| ( %d, %d) |\n",places[i].name, places[i].category, places[i].x,places[i].y); //test to see data
i++;
}
}
fclose(file);
}
这是从以下内容中读取的信息:
STARBUCKS COFFEE,cafeteria,7,11
Restaurant UNIVERSAL CLUB,cafeteria,18,16
PHONON CAFE ROOM,cafeteria,7,12
Craig's Cafe SEATTLE ESPRESS,cafeteria,18,11
Cafeteria NANAMI-TEI,cafeteria,11,7
IB Cafe,cafeteria,11,9
Restaurant Chez Jiroud,cafeteria,15,10
Labo Shop (NU CO-OP Shop),shop,29,19
NU CO-OP North,shop,11,5
Family Mart,shop,13,11
South Cafeteria,cafeteria,4,17
NU CO-OP South,shop,5,17
Amenity House,shop,6,17
FOREST Books & Cafe,cafeteria,19,7
Green Salon Higashiyama,cafeteria,21,8
Toyoda Auditorium / Symposion,Convention facility,17,15
Noyori Conference Hall,Convention facility,21,14
E & S Hall,Convention facility,16,9
Sakata & Hirata Hall,Convention facility,19,11
以下是我实际得到的内容:
| | | ( 0, 0) |
|☺ | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
| | | ( 0, 0) |
如果不是那种奇怪的笑脸,我会认为它不是在阅读任何东西,或者没有把它转移到结构中,但是因为它是我受到了保护。非常欢迎任何建议,谢谢你的时间!
答案 0 :(得分:1)
尝试fscanf
从文件而不是scanf
读取,并使用%[^,]
(除了',#39;之外的所有内容)而不是%s
。
Codesnip:while(fscanf(file, "%[^,],%[^,],%d,%d", &places[i].name, &places[i].category, &places[i].x, &places[i].y) == 4)