Reputation: 63
I have a function that reads in a file that looks like the following into a structure. I'm trying to make sure that the structure is being filled properly; and, it is filled correctly for Gender, Height, and Weight. However, I'm having trouble verifying that the Name (character array) part of it is filling properly.
Example file to read in:
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 Definition:
struct canData
{
char name[50];
char gender;
float height;
float weight;
}CD[structSize]; // end struct BP
Part of the loop that reads the file in:
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
Currently, my output is as follows:
(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)
...
Thanks for any insight! I'm a C beginner, so I may be missing something silly.
Upvotes: 1
Views: 68
Reputation: 837
scanf
expects a pointer to initial byte of an array, when you are reading a string. So dont use&
when you are passing as an argument. fscanf(fp, "%[^,]", name)
should work.
name
will be converted to a pointer when used in an expression.
http://pubs.opengroup.org/onlinepubs/009695399/functions/fscanf.html
Upvotes: 1