Thread: Help with Sorting Structures in Database

  1. #1
    Registered User
    Join Date
    Nov 2012
    Posts
    9

    Help with Sorting Structures in Database

    Howdy! I want to sort the data inputed 3 different ways, as a choice from the user. Either Alphabetical by name, by ascending order for the ID or grades. How would I manipulate the program to sort the strings? maybe by using strcmp()?
    T
    his is also from the assignment "To sort the record, one can use a bubble sort function modified to work with name/id/grade"


    Code:
    #include <stdio.h> 
    #include <string.h>
     struct student { 
     int student_id; 
     char name[30]; 
     char grade[15]; 
    }; 
    
    int i; 
    struct student stu[20]; 
    int students;
    int sort; 
    
    int main(void) 
    { 
    printf("How many students in the Class?: ");
      scanf("%d", &students);
      for(i = 0; i < students; i++)
        { 
    printf("Enter name: "); 
      scanf("%s",stu[i].name); 
    printf("Enter id: "); 
      scanf("%d", &stu[i].student_id); 
    printf("Enter grade: "); 
      scanf("%s",stu[i].grade); 
    printf("\n");
        } 
    
    printf("how do you want to sort the records? [0 - name, 1 - id, 2 - grade]: ");
        scanf("%d", &sort);
    
    if (sort==0)
      for(i = 0; i < students; i++) 
      printf(" Name: %s \n Sudent id: %d\n Grade: %s\n\n", 
      stu[i].name,stu[i].student_id,stu[i].grade); 
    
    else if (sort==1)
      for(i = 0; i < students; i++) 
      printf(" Student id: %d \n Name: %s\n Grade: %s\n\n", 
      stu[i].student_id,stu[i].name, stu[i].grade); 
    
    else if (sort==2)
      for(i = 0; i < students; i++)         
     printf(" Grade: %s \n Name: %s\n Student id: %d\n\n", 
      stu[i].grade,stu[i].name,stu[i].student_id); 
             
    return0; 
    }
    
    Last edited by soccer1223334; 11-28-2012 at 11:38 AM.

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Welcome to the forum!

    It's good to get in the habit of reading the documentation for functions you plan on using or may want to use. Here: strcmp(3): compare two strings - Linux man page. In this case, the critical part is the "Return Value" section. So if you compare the result of strcmp to 0, you will know if s1 was less than or greater than (or equal to) s2.

    So yes, strcmp will work for sorting strings, or more precisely for comparing strings. That comparison will have to be used in a sorting algorithm. If you are allowed, I suggest the standard C function qsort (qsort(3): sorts array - Linux man page) to sort your stu array. You can write simple comparison functions that operate on the name, ID or grade, and pass those as the comparison functions for qsort, based on what sort type the user picks. If you are supposed to write your own, something like insertion sort (Insertion sort - Wikipedia, the free encyclopedia) is easy to implement and efficient enough for your small array.

    Lastly, when posting code, please copy-paste your program code as plain text. Our forum will handle the syntax highlighting and line numbering. And make sure you have good formatting, clear, consistent indentation, etc. If your code is hard to read, we're less likely to help.

    EDIT: Google "c qsort struct example" or similar for many examples of how to use qsort with an array of structs.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    So where is your attempt at sorting?

    PS, when pasting your code, make sure you "paste as text".
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Nov 2012
    Posts
    9

    Sorting

    This is what I have so far, I think im close but im still getting errors that I havent declared things in the bottom fxn.
    Am I on the right track at least?

    Code:
    #include <string.h>
    #include <stdio.h>
    struct student 
        { 
         int student_id; 
         char name[30]; 
         char grade[15]; 
        };
    int i; 
    struct student stu[20]; 
    int students;
    int input; 
    
    int main(void) 
    { 
      printf("How many students in the Class?: ");
      scanf("%d", &students);
      for(i = 0; i < students; i++)
    
        { 
         printf("Enter name: "); 
         scanf("%s",stu[i].name); 
         printf("Enter id: "); 
         scanf("%d", &stu[i].student_id); 
         printf("Enter grade: "); 
         scanf("%s",stu[i].grade); 
         printf("\n");
        }
    
    
    
           printf("how do you want to sort the records? [0 - name, 1 - id, 2 - grade]: ");
        scanf("%d", &input);
    
        void sort(struct student st[],int cnt,int choice);
        {
        int i,j;
        struct student temp;
    
        for(i=0;i<cnt-2;i++)
            {
        for(j=0;j<cnt-1;j++)
                {
        if(
        (choice==0 && strcmp(st[j].last_name,st[j+1].last_name)>0)
        ||
        (choice==1 && st[j].student_id>st[j+1].student_id)
        ||
        (choice==2 && st[j].grade>st[j+1].grade)
        )
                    {
        temp=st[j];
        st[j]=st[j+1];
        st[j+1]=temp;
                    }
                }
            }
        }    
        return;
    }

  5. #5
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    A typical small program seems like this
    Code:
    #include <stdio.h>
    
    void myFunction(int a);
    
    int main(void)
    {
            int a;
            a = 5;
           myFunction(a);
    
           return 0;
    }
    
    void myFunction(int a)
    {
           printf("%d\n",a);
    }
    Compare your's program structure.
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  6. #6
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    > im still getting errors that I havent declared things in the bottom fxn.
    How about you provide those error messages along with line numbers (copy-paste so they're exact). That will help us immensely.

    Here is what your code looks like when it's properly indented/formatted:
    Code:
    #include <string.h>
    #include <stdio.h>
    struct student
    {
        int student_id;
        char name[30];
        char grade[15];
    };
    int i;
    struct student stu[20];
    int students;
    int input;
    
    
    int main(void)
    {
        printf("How many students in the Class?: ");
        scanf("%d", &students);
        for(i = 0; i < students; i++)
    
    
        {
            printf("Enter name: ");
            scanf("%s",stu[i].name);
            printf("Enter id: ");
            scanf("%d", &stu[i].student_id);
            printf("Enter grade: ");
            scanf("%s",stu[i].grade);
            printf("\n");
        }
    
    
    
    
    
    
        printf("how do you want to sort the records? [0 - name, 1 - id, 2 - grade]: ");
        scanf("%d", &input);
    
    
        void sort(struct student st[],int cnt,int choice);
        {
            int i,j;
            struct student temp;
    
    
            for(i=0;i<cnt-2;i++)
            {
                for(j=0;j<cnt-1;j++)
                {
                    if(
                            (choice==0 && strcmp(st[j].last_name,st[j+1].last_name)>0)
                            ||
                            (choice==1 && st[j].student_id>st[j+1].student_id)
                            ||
                            (choice==2 && st[j].grade>st[j+1].grade)
                      )
                    {
                        temp=st[j];
                        st[j]=st[j+1];
                        st[j+1]=temp;
                    }
                }
            }
        }
        return;
    }
    Notice how much easier it is to follow the flow of this? Notice how you can see glaring errors in program structure/flow, like how your sort function is actually inside main? Nested functions like that are not allowed in C. Move it outside main (I suggest putting it above main).

    Also, you use global variables. Global variables are bad, read this link. Declare them in the appropriate function (probably main), and pass them to other functions as needed.

    You seem to have a stray semicolon at the end of your sort function.

    Otherwise, you seem to be on the right track. Your sort logic looks close to working, if it doesn't work already.

  7. #7
    Registered User
    Join Date
    Nov 2012
    Posts
    9
    Thank you! that helped a lot! I fixed all the compiling problems but when i run the program it doesnt sort anything and skips the fxn called... am i declaring something wrong?

    Code:
    #include <string.h>
    #include <stdio.h>
    struct student
    {
        int student_id;
        char name[30];
        char grade[15];
    };
    int i;
    struct student stu[20];
    int students;
    int input;
    void sort(struct student st[],int cnt,int choice);
     
     
    int main(void)
    {
        printf("How many students in the Class?: ");
        scanf("%d", &students);
        for(i = 0; i < students; i++)
     
     
        {
            printf("Enter name: ");
            scanf("%s",stu[i].name);
            printf("Enter id: ");
            scanf("%d", &stu[i].student_id);
            printf("Enter grade: ");
            scanf("%s",stu[i].grade);
            printf("\n");
        }
     
        printf("how do you want to sort the records? [0 - name, 1 - id, 2 - grade]: ");
        scanf("%d", &input);
     }
     
        void sort(struct student st[],int cnt,int choice)
        {
            int i,j;
            struct student temp;
     
     
            for(i=0;i<cnt-2;i++)
            {
                for(j=0;j<cnt-1;j++)
                {
                    if(
                            (choice==0 && strcmp(st[j].name,st[j+1].name)>0)
                            ||
                            (choice==1 && st[j].student_id>st[j+1].student_id)
                            ||
                            (choice==2 && st[j].grade>st[j+1].grade)
                      )
                    {
                        temp=st[j];
                        st[j]=st[j+1];
                        st[j+1]=temp;
                    }
                }
            }
            return;
        }
    Last edited by soccer1223334; 11-29-2012 at 02:08 PM. Reason: Edit: Fix Text

  8. #8
    Registered User
    Join Date
    Nov 2012
    Posts
    9
    Oh... I just saw your post. Thank you! In our class we never learned how to indent and make it look all nice... Thank you for the help!

  9. #9
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Edit your last post and fix the wonky font you keep using. Paste your program in as plain text, and make sure you're using spaces (not tabs) for indentation, so it looks right on the forum. That will also allow the forum to add line numbers and syntax highlighting. It should look more or less like the code in my last post.

  10. #10
    Registered User
    Join Date
    Nov 2012
    Posts
    9
    How would a printf statement be implemented here in order for the sorting fxn to be able to be printed in accordance with the user input (0, 1 or 2). something like?
    Code:
     printf(" %s, ID: %d, has a grade: %s\n\n", st[i].name,st[i].student_id,st[i].grade);
    The output should apparently look something like this:
    How do you want to sort the records? (0 - name, 1 - id, 2 - grade): 2 (user input)



    Sarah, ID:53214, has grade: A
    Jack, ID:54673, has grade: B
    Daniel, ID:61234, has grade: B
    Monica, ID:71234, has grade: C
    Chris, ID:64351, has grade: F

  11. #11
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    That printf looks like it will work just fine. Try it out to make sure.

    It's not sorting anything because you never call sort. To actually sort your records, after you read the user input, call sort and pass in the choice variable.

    Also, you don't need a return; at the end of a function returning void, it is implied, but you should return a value from main, so stick a return 0; at the end.

  12. #12
    Registered User
    Join Date
    Nov 2012
    Posts
    9
    I inputed this for loop and printf statement into the program. it does loop though all the students correctly but what should I identify %s, %d and %s in the printf statement to be? Does it have to be from the Sort function?

    Code:
     }
    //...previous code
        printf("how do you want to sort the records? [0 - name, 1 - id, 2 - grade]: ");
        scanf("%d", &input);
    
        sort(stu,students,input);
    
            for(i = 0; i < students; i++) 
              {           
             printf(" %s, ID: %d, has a grade: %s\n\n", 
             stu[i].name,stu[i].student_id,stu[i].grade); 
              }
        return 0;
     }
     
        void sort(struct student st[],int cnt,int choice)
        {//more code...

  13. #13
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    I think that printing code is fine. You want to print the elements of the stu array, which you do. You do this after they have been sorted, to show the user the records sorted as they requested.

    Note, if I input the following 5 students:
    Code:
    Sarah 53214 A
    Jack 54673 B
    Daniel 61234 B
    Monica 71234 C
    Chris 64351 F
    then sort by name, I get the following output:
    Code:
    Daniel, ID: 61234, has a grade: B
    Chris, ID: 64351, has a grade: F
    Jack, ID: 54673, has a grade: B
    Monica, ID: 71234, has a grade: C
    Sarah, ID: 53214, has a grade: A
    Notice Daniel and Chris are out of order. Your just need one more iteration in your outer sort loop:
    Code:
    for(i=0;i<cnt-1;i++)  // note, cnt-1

  14. #14
    Registered User
    Join Date
    Nov 2012
    Posts
    9
    I GOT IT! Thank you for the help!
    Last edited by soccer1223334; 11-29-2012 at 05:24 PM.

  15. #15
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Post the current version of your code with the exact input you are giving it. Unfortunately, I have to leave soon, so hopefully somebody else will come along and help you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Music database using Linked Data Structures. halp!
    By Chucker in forum C Programming
    Replies: 1
    Last Post: 03-28-2012, 04:34 PM
  2. Structures within structures for a database
    By Holtzy in forum C Programming
    Replies: 2
    Last Post: 04-30-2008, 07:06 AM
  3. Sorting structures
    By sybariticak47 in forum C++ Programming
    Replies: 14
    Last Post: 05-09-2006, 03:44 AM
  4. Help with sorting a text file database
    By bds824 in forum C Programming
    Replies: 5
    Last Post: 02-14-2006, 11:58 PM
  5. Sorting structures
    By RedRum in forum C++ Programming
    Replies: 2
    Last Post: 05-23-2002, 12:19 PM

Tags for this Thread