无法读取以逗号结尾的字符串

我有一个函数,它读入一个类似于下面的文件到一个结构中。 我正在努力确保结构正确填充; 并且,它已正确填充性别,身高和体重。 但是,我无法validation它的名称(字符数组)部分是否正确填充。

要读入的示例文件:

Name,Gender,Height,Weight Tanner,M,71.8,180.25 John,M,70.75,185.3 Parker,F,65.25,120.3 Meeks,M,57.25,210.2 Big,M,57.5,150.1 Jackson,F,52.1,163.4 

结构定义:

 struct canData { char name[50]; char gender; float height; float weight; }CD[structSize]; // end struct BP 

读取文件的循环的一部分:

 char name[50]; char gender; float height; float weight; int position = 0; filePtr = fopen(fileName, "r"); // open file if (filePtr == NULL) // error check opening file { printf("Opening file failed. Please reenter filename."); exit(1); // WILL THIS RETURN TO MENU? } // end if // skip header line of file char buffer[100]; fgets(buffer, 100, filePtr); while (fscanf(filePtr, "%[^,], %[^,], %f, %f", &name, &gender, &height, &weight) == 4) // read in { printf("%s\n", name); // DEBUG ATTEMPT printf("%s\n", CD[position].name); // DEBUG ATTEMPT printf("%f\n", weight); // DEBUG ATTEMPT strcpy(CD[position].name, name); CD[position].gender = gender; CD[position].height = height; CD[position].weight = weight; position++; iCount++; } // end while 

目前,我的输出如下:

 (space where name should be) (space where CD[position].name should be) 180.25 (space where name should be) (space where CD[position].name should be) 185.3 (space where name should be) (space where CD[position].name should be) 120.3 (space where name should be) (space where CD[position].name should be) ... 

感谢您的任何见解! 我是C初学者,所以我可能会遗漏一些愚蠢的东西。

当您读取字符串时, scanf需要一个指向数组初始字节的指针。 所以当你作为一个论点传递时,不要使用&fscanf(fp, "%[^,]", name)应该有效。

在表达式中使用时, name将转换为指针。

http://pubs.opengroup.org/onlinepubs/009695399/functions/fscanf.html