Sort and Output structure in order - C Structure

C examples for Structure:Structure Value

Description

Sort and Output structure in order

Demo Code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#define MAXTITL 40//from  w ww .ja  v a  2 s.  com
#define MAXAUTL 40
#define MAXBKS 100

struct book
{
  char title[MAXTITL];
  char author[MAXAUTL];
  float value;
};

char * get(char *, int);
void titlesort(struct book **books, int count);
void valuesort(struct book **books, int count);

int main(void)
{
  struct book *my[MAXBKS];
  char temp[MAXTITL];
  int count = 0;
  int index;

  while (count < MAXBKS && get(temp, MAXTITL) != NULL
       && temp[0] != '\0')
  {
    my[count] = (struct book *) malloc(sizeof(struct book));
    strncpy(my[count]->title, temp, MAXTITL);

    printf("Now enter the author.\n");
    get(my[count]->author, MAXAUTL);

    printf("Now enter the value.\n");
    scanf("%f", &my[count]->value);

    while (getchar() != '\n')
      continue;

    if (count < MAXBKS)
      printf("Enter the next title.\n");

    count++;
  }

  if (count > 0)
  {
    printf("Here is the list of your books in the original order:\n");
    for (int i = 0; i < count; i++)
      printf("%s by %s: $%.2f\n", my[i]->title, my[i]->author, my[i]->value);
    puts("");

    // sorted by title
    printf("Here is the list of your books alphabetized by title:\n");
    titlesort(my, count);
    for (int i = 0; i < count; i++)
      printf("%s by %s: $%.2f\n", my[i]->title, my[i]->author, my[i]->value);
    puts("");

    // sorted by value
    printf("Here is the list of your books ordered by value:\n");
    valuesort(my, count);
    for (int i = 0; i < count; i++)
      printf("%s by %s: $%.2f\n", my[i]->title, my[i]->author,my[i]->value);
  }

  for (int i = 0; i < count; i++)
    free(my[count]);

  return 0;
}

// replaces first newline with null
char * get(char *string, int n){
  char *return_value = fgets(string, n, stdin);
  while (*string != '\0'){
    if (*string == '\n'){
      *string = '\0';
      break;
    }

    string++;
  }

  return return_value;
}

void titlesort(struct book **books, int count){
  struct book *temp;
  for (int i = 0; i < count - 1; i++)  {
    for (int j = i + 1; j < count; j++){
      if (tolower(books[i]->title[0]) > tolower(books[j]->title[0]))
      {
        temp = books[i];
        books[i] = books[j];
        books[j] = temp;
      }
    }
  }
}

void valuesort(struct book **books, int count){
  struct book *temp;
  for (int i = 0; i < count - 1; i++){
    for (int j = i + 1; j < count; j++){
      if (books[i]->value > books[j]->value){
        temp = books[i];
        books[i] = books[j];
        books[j] = temp;
      }
    }
  }
}

Result


Related Tutorials