I have this program that extracts book data(title, isbn, authors and publisher) from a file and then populates 3 structs. The structs are all correctly populated and the command "t" that prints all the books alphabetically in order is working correctly. So everything up until that point works but then if I try to use the "i 'isbn'" (ex.: i 9780321942050) command it doesn't work. It prints some weird characters and I've tried everything in the range of function of my brain to try and fix it but nothing worked. From what I could understand the problem is in the vecRefSearchIsbn function and what it returns because everything is being passed correctly up until that point. I don't have that much knowledge about pointers so I may be missing something but I've tried a lot of things so I'm not going to list them all. I provided the main function and the vecRefSearchIsbn function because that is where I think the problem resides but if someones thinks that the problem is elsewhere I won't hesitate to provide any other functions.
This is what I get in the output:
Digite um comando (t, i + isbn, q): i 9780321942050
Title:p▬┼%7☻
ISBN: 0z┼%7☻
Authors: ░É┼%7☻
Publisher: `¡┼%7☻
typedef struct {
char *title;
char isbn[MAX_ISBN];
char *authors;
char *publisher;
} Book;
typedef struct{
Book **refs;
int size;
int space;
} VecBookRef;
typedef struct{
VecBookRef *titleVec;
VecBookRef *isbnVec;
} DynCollection;
#include <stdio.h>
#include <stdlib.h>
#include "vector.h"
#include "book.h"
#include "collection.h"
#include "splitfield.h"
int main(){
char input[100];
DynCollection *col;
FILE *f=fopen("dados.csv", "r");
if(f==NULL){
printf("Erro ao abrir ficheiro");
return 0;
}
vecRefCreate();
col=collecBuild(f);
if(col==NULL){
printf("Erro ao criar coleção");
return 0;
}
fclose(f);
do{
printf("\nDigite um comando (t, i + isbn, q): ");
fgets(input, sizeof(input), stdin);
int inputLen=strlen(input);
if(inputLen==2 && input[0]=='t'){
vecRefScan(col->titleVec, NULL, printBook);
}
else if(inputLen>2 && input[0]=='i' && input[1]==' '){
char isbn[MAX_ISBN];
sscanf(input+2, "%s", isbn);
if(strlen(isbn)!=13){
printf("\nISBN invalido\n");
continue;
}
Book *b=vecRefSearchIsbn(col->isbnVec, isbn);
if(b!=NULL){
printBook(b, NULL);
}else{
printf("\nNao foi encontrado um livro com o ISBN inserido\n");
continue;
}
}
if(inputLen==2 && input[0]=='q'){
collecFree(col);
printf("Memoria limpa");
}
}while(input[0]!='q');
return 0;
}
Book *vecRefSearchIsbn(VecBookRef *vec, char *isbn){
int comparator(const void *key, const void *book){
const char *isbn=(const char *)key;
const Book *b=*(const Book **)book;
return strcmp(isbn, b->isbn);
}
Book *b=(Book*)bsearch(isbn, vec->refs, vec->size, sizeof(Book *), comparator);
if(b!=NULL){
return b;
}else return NULL;
}
void printBook(Book *b, void *context){
printf("\nTitle:%s\nISBN: %s\nAuthors: %s\nPublisher: %s\n", b->title, b->isbn, b->authors, b->publisher);
}