Hello everyone, I hope you're having a fantastic day!
I'm having a problem with adding one line of a file as a string in a struct. The struct kind of works like a list.
We have a .txt file that has names (that can have spaces!), so we need the whole line to be a string.
The next line will have two numbers that we need to keep in two ints (that part is working as it should.).
And it just repeats 9 times in the file.
I'm using a fscanf with "%[^\n]" to read the whole line, and when I print that string it gives me what it should.
But when I use my function to print the name of the struct as well as other variables, the name is always wrong.
Here's my code as well as screenshots to help:
struct ListResto* readRestos(char* nameFile) {
// OPENING THE FILE
FILE *p1;
p1 = fopen(nameFile, "r");
if (p1 == NULL) {
printf("Error in opening file.\n");
return NULL;
}
// CREATING THE STRUCT AND VARIABLES
struct ListResto* l = createEmptyList();
struct Resto* temp = NULL;
char name[30];
int check = 0;
int lines = 0;
while (check != EOF) {
if (lines % 2 == 0) { // Used to see if we're at a line with text or other variables.
fscanf(p1, "%[^\n]", name);
printf("Name: %s\n", name);
lines++;
nameResto = name;
} else {
// I got rid of other variables for visibility.
temp = createResto(name, quality, distance);
addFirst(l, temp);
lines++;
}
check = fgetc(p1);
}
fclose(p1);
return l;
}
struct Resto* createResto(char* name) {
struct Resto* r = malloc(sizeof(struct Resto));
r->name = name;
// I got rid of other variables for visibility.
return r;
}
I'm pretty sure the thing to print a "Resto" struct is working considering that I just had to modify few things from another code.
Thanks for reading, wishing you a fantastic day!