I am trying to make a program that uses a struct to store the title the author and the pages of a book.Then I want it to find which one has the lowest amount of pages and then use a void function to print its details.Whenever I run the code it seems to work but it always prints the wrong values.I am not 100% familiar with structs yet and I was wondering if somebody had an answer to why this isnt working.
#include <stdio.h>
#include <stdlib.h>
#define N 3
struct book{
char title[N];
char author[N];
int pages[N];
};
void printbook(struct book);
int main(){
int i,thesh;
int min;
struct book vivlio[N];
for(i=0;i<3;i++){
printf("\n\ndwse titlo tou vivliou: ");
scanf("%s",vivlio[i].title);
printf("\ndwse suggrafea tou vivliou: ");
scanf("%s",vivlio[i].author);
printf("\ndwse selides tou vivliou: ");
scanf("%d",vivlio[i].pages);
}
min = vivlio[0].pages;
thesh = 0;
for(i=1;i<3;i++){
if(vivlio[i].pages<min){
min = vivlio[i].pages;
thesh = i;
}
}
printbook(vivlio[thesh]);
return 0;
}
void printbook(struct book x){
printf("\n\nTo vivlio me tis ligoteres selides exei ton titlo: %s",x.title);
printf("\n\nTo vivlio me tis ligoteres selides exei ton suggrafea: %s",x.author);
printf("\n\nTo vivlio me tis ligoteres selides exei arithmo selidwn: %d",x.pages);
}
title
and author
need to be longer than 3 character, which only allows room for 2 characters plus the null terminator. N
is the number of books, it shouldn't also be used as the number of characters.
pages
should just be a single integer, not an array. Then when you're reading it with scanf()
, you need to pass the address of the integer with &
.
You should use N
as the limit in your for
loops, rather than hard-coding 3
.
You should end your last line of output with a newline, the the next shell prompt won't be printed on the same line.
#include <stdio.h>
#include <stdlib.h>
#define N 3
#define MAXTITLE 20
#define MAXNAME 30
struct book{
char title[MAXTITLE];
char author[MAXNAME];
int pages;
};
void printbook(struct book);
int main(){
int i,thesh;
int min;
struct book vivlio[N];
for(i=0;i<N;i++){
printf("\n\ndwse titlo tou vivliou: ");
scanf("%s",vivlio[i].title);
printf("\ndwse suggrafea tou vivliou: ");
scanf("%s",vivlio[i].author);
printf("\ndwse selides tou vivliou: ");
scanf("%d",&vivlio[i].pages);
}
min = vivlio[0].pages;
thesh = 0;
for(i=1;i<N;i++){
if(vivlio[i].pages<min){
min = vivlio[i].pages;
thesh = i;
}
}
printbook(vivlio[thesh]);
return 0;
}
void printbook(struct book x){
printf("\n\nTo vivlio me tis ligoteres selides exei ton titlo: %s",x.title);
printf("\n\nTo vivlio me tis ligoteres selides exei ton suggrafea: %s",x.author);
printf("\n\nTo vivlio me tis ligoteres selides exei arithmo selidwn: %d\n",x.pages);
}
You probably also shouldn't be using %s
to read the name and title. This only extracts a single word from the input, so you won't be able to enter names and titles with spaces.