Thread: Word Sort

  1. #1
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321

    Question Word Sort

    Hello!

    I have written this code which is supposed to take five names as input and then arrange them in alphabetical order. It got compiled easily but after I input those 5 names, the window closes automatically even when I have getch() in place. Also, I don't think I have written the function which sorts the names [word_swap()] any good.

    Please help me set this code right....(I know ive made a mess, sorry for that )

    Thanks!

    Code:
    #include<stdio.h>
    #include<conio.h>
    void word_swap(char*,char*);  /*I don't think I have written the definition of this function correctly*/
    int main()
    {
        char temp[20],names[5][20];
        int x,y,z;
        for(x=0;x<5;x++)
        {
                        printf("\nEnter a name :");
                        scanf("&#37;s",&temp);
                        for(y=0;names[x][y]!='\0';y++)
                        {
                                                     names[x][y]=temp[y];
                        }
                        names[x][y]='\0';
        }
        
        for(x=0;x<5;x++)
        {
                 for(z=x+1;z<5;z++)
                 {
                                   for(y=0;names[x][y]!='\0'&& names[z][y] !='\0';y++)
                                   {
                                                               if((int)names[x][y]>(int)names[z][y])
                                                               word_swap(&names[x][0],&names[z][0]);
                                   }
                 }
        }
        for(x=0;x<5;x++)
        {
                        
                        printf("\n");
                        for(y=0;names[x][y]!='\0';y++)
                                                      printf("%c",names[x][y]);
        }
        
        getch();
        return 0;
    }
    
    
    void word_swap(char*str1,char*str2)
    {
         int n=0;
         char temp;
         while(n!=2)
         {
                   temp=*str1;
                   *str1=*str2;
                   *str2=temp;
                    str1++;
                    str2++;
                    if(*str1=='\0')
                                   n++;
                    if(*str2=='\0')
                                   n++;
         }
                                            
    }
    Last edited by abh!shek; 02-02-2008 at 09:09 AM.

  2. #2
    Beautiful to C Aia's Avatar
    Join Date
    Jun 2007
    Posts
    124
    scanf is a bad choice for reading a string from user. It leaves characters in the buffer. In the best scenario is leaving the ENTER key which getch() is picking up.

    By the way, temp is a pointer to the first element of the subscript when you pass it to scanf, so you don't need the &.

  3. #3
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Better to use fgets instead of scanf to read strings. Scanf can be dangerous when reading strings as well. See my signature.
    And you could really use some less spaces for each indentation level. 4 is more than enough.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  4. #4
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321
    Quote Originally Posted by Aia View Post
    temp is a pointer to the first element of the subscript when you pass it to scanf, so you don't need the &.
    Thanks for that . I wonder why it didn't give an error.

  5. #5
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321
    I replaced
    Code:
    scanf("&#37;s",&temp);
    with
    Code:
     fgets(temp,20,stdin);
    But the window is still closing as soon as I input all the five names.

  6. #6
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321
    Have i written the word_swap() definition correctly ?

  7. #7
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Post your updated code please.
    Mainframe assembler programmer by trade. C coder when I can.

  8. #8
    Beautiful to C Aia's Avatar
    Join Date
    Jun 2007
    Posts
    124
    Quote Originally Posted by abk View Post
    Have i written the word_swap() definition correctly ?
    If you are referring to the prototype void word_swap( char *, char * ); Yes it it correct. The compiler only needs to know that
    word_swap accepts two string pointers.

    fgets() will read up to 19 characters and it will insert a '\0' at the end of the string.
    some possibilities:
    You enter a name sorter or up to 18 characters, fgets reads everything including the ENTER key (newline) and attachs a terminator '\0' at the ending.

    You enter a name exactly 19 long and press enter. fgets reads those characters, terminates it with '\0' and leaves ENTER key behind for the next call to pick it up.

    You enter a name longer that 20 characters. Any thing beyond 19 characters is left in the buffer input, including the ENTER key.

    BTW, I am assuming you are practicing loops and accessing subscripts of arrays. Because there's already standard functions that will do the same thing you're trying to achieve.

    After you find what's the problem closing your program right away, we'll talk about why your code will not do what you intend.
    Last edited by Aia; 02-02-2008 at 10:39 AM.

  9. #9
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321
    Updated code

    Code:
    #include<stdio.h>
    #include<conio.h>
    void word_swap(char*,char*);  /*I don't think I have written the definition of this function correctly*/
    int main()
    {
        char temp[20],names[5][20];
        int x,y,z;
        for(x=0;x<5;x++)
        {
                        printf("\nEnter a name :");
                        fgets(temp,20,stdin);
                        for(y=0;names[x][y]!='\0';y++)
                        {
                                                     names[x][y]=temp[y];
                        }
                        names[x][y]='\0';
        }
        
        for(x=0;x<5;x++)
        {
                 for(z=x+1;z<5;z++)
                 {
                                   for(y=0;names[x][y]!='\0'&& names[z][y] !='\0';y++)
                                   {
                                                               if((int)names[x][y]>(int)names[z][y])
                                                               word_swap(&names[x][0],&names[z][0]);
                                   }
                 }
        }
        for(x=0;x<5;x++)
        {
                        
                        printf("\n");
                        for(y=0;names[x][y]!='\0';y++)
                                                      printf("&#37;c",names[x][y]);
        }
        
        getch();
        return 0;
    }
    
    
    void word_swap(char*str1,char*str2)
    {
         int n=0;
         char temp;
         while(n!=2)
         {
                   temp=*str1;
                   *str1=*str2;
                   *str2=temp;
                    str1++;
                    str2++;
                    if(*str1=='\0')
                                   n++;
                    if(*str2=='\0')
                                   n++;
         }
                                            
    }

  10. #10
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321
    Quote Originally Posted by Aia View Post
    If you are referring to the prototype void word_swap( char *, char * ); Yes it it correct.
    No I am talking about this code:
    Code:
    void word_swap(char*str1,char*str2)
    {
         int n=0;
         char temp;
         while(n!=2)
         {
                   temp=*str1;
                   *str1=*str2;
                   *str2=temp;
                    str1++;
                    str2++;
                    if(*str1=='\0')
                                   n++;
                    if(*str2=='\0')
                                   n++;
         }
                                            
    }

  11. #11
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Code:
                         for(y=0;names[x][y]!='\0';y++)
                        {
                                                     names[x][y]=temp[y];
                        }
                        names[x][y]='\0';
    This won't work. The names array doesn't contain anything when you declared it, so it doesn't make sense to use what names[x][y] contains as a condition for the loop.

    What might be a better solution is to read five names and then copy them into the names array explicitly with a string_copy function like strcpy(). You can write your own strcpy() if you want to, it's really easy. Just assign each character from the source to the destination until you reach the source's '\0'. Then assign '\0' to the destination.

    Then you can focus on sorting. word_swap is ok, but only when str1 and str2 are the same length.

  12. #12
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Come on, abk, you use way too many spaces for indentation. Lessen it a bit. It makes it look nicer and people don't have to scroll to read the code. It's very simple.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #13
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Your lexicographical ordering is wrong.
    word_swap should not be within 3 nested loops. Right now it might swap two words many times over. The inner loop should be replaced with a strcmp.
    Then you can find out what order the words should be in and THEN decided ONCE whether to swap them or not.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  14. #14
    Beautiful to C Aia's Avatar
    Join Date
    Jun 2007
    Posts
    124
    If I may suggest.
    Write small pieces of code and compile often.
    e.g
    Write the part that will get the input into an array of strings. ( It is not necessary to go through a temporal string variable )
    Compile.
    Write a test loop that will display each string
    Compile.
    Notice the unwanted newline in each string.
    Write the part that will eliminate the newline in each string.
    Compile.
    In a different file write a function that swap strings
    Compile.
    Test the function. If is bug free, add to the project
    writing the part that loops through the strings and compare them.
    Compile.
    Debugging will be easier when you have tested every little portion and know that is working the way intended.

    BTW You don't need #include<conio.h> and getch. A simple standard getchar() would do very well.
    When the eagles are silent, the parrots begin to jabber. ~Winston Churchill

  15. #15
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321
    Quote Originally Posted by Elysia View Post
    Come on, abk, you use way too many spaces for indentation. Lessen it a bit. It makes it look nicer and people don't have to scroll to read the code. It's very simple.
    Sorry for that, but its my IDE's fault. It indents automatically. I will take care abt it next time i post.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Hangman game and strcmp
    By crazygopedder in forum C Programming
    Replies: 12
    Last Post: 11-23-2008, 06:13 PM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  3. seg fault at vectornew
    By tytelizgal in forum C Programming
    Replies: 2
    Last Post: 10-25-2008, 01:22 PM
  4. Assembly Tutorials
    By JoshR in forum A Brief History of Cprogramming.com
    Replies: 13
    Last Post: 06-11-2005, 09:56 AM
  5. Word Count
    By simple in forum C Programming
    Replies: 12
    Last Post: 10-04-2002, 10:47 PM