I'm a student tryig to print 6 lines I have inserted into a txt document called test.txt
The test file is simple plain text in a .txt
with the following text, all on its own line:
Nikolaj
Ljorring
m
20
182
200
However, I need to put the loaded data into a struct which look likes this:
struct profile_info
{
char first_name[30];
char last_name[30];
char gender;
int age;
int height;
double weight;
};
And a loader / printing function that looks like so:
void user_profile_loader(struct profile_info user_profile)
{
FILE *file_pointer;
file_pointer = fopen("test.txt", "r");
fscanf(file_pointer, "%s", &user_profile.first_name);
fscanf(file_pointer, "%s", user_profile.last_name);
fscanf(file_pointer, "%c", &(user_profile.gender));
fscanf(file_pointer, "%d", &(user_profile.age));
fscanf(file_pointer, "%d", &(user_profile.height));
fscanf(file_pointer, "%d", &(user_profile.weight));
printf("%s \n%s \n€c \n%d \n%d \n%lf", &user_profile.first_name, &user_profile.last_name,
user_profile.gender, user_profile.age, user_profile.height, user_profile.weight);
fclose(file_pointer);
}
However, my output looks like so:
Nikolaj
Ljorring
(wierd C with a line beneath it)c [So a wierd C followed by a normal lowercase c]
10
5
0.000000
fscanf(file_pointer, "%s", &user_profile.first_name);
^ no need of & here
And here -
fscanf(file_pointer, "%d", &(user_profile.weight));
You use %d
to read a double
value .You pass wrong argument it invokes UB .Use %lf
here.
In your printf
-
printf("%s \n%s \n€c \n%d \n%d \n%lf", &user_profile.first_name,
&user_profile.last_name,user_profile.gender, user_profile.age, user_profile.height, user_profile.weight);
What is \\n€c
? You should use specifier %c
.
Note - You should check return of fopen
and fscanf
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.