Thread: using strlen and finding shortest and longest words

  1. #1
    Unregistered
    Guest

    using strlen and finding shortest and longest words

    program is to let user input series of words and when user inputs word of length 4 characters, it stops.
    It should sort the words alphabetically, so if a group of same-length words is longest/shortest, it outputs longest as last alphabetically, shortest as first alphabetically.
    My code is not pulling the longest word correctly.
    What is the problem here????


    Code:
    #include <stdio.h>
    #include <string.h>
    #define LENGTH 20
    
    
    int read_line(char str[], int n);
    
    main()
    {
        char largest[LENGTH];
        char smallest[LENGTH];   /*  is the size of array okay */
        char input[LENGTH];
        int len;
        
        printf("Enter word: ");
        read_line(input, LENGTH);
        len = strlen(input); 
        strcpy(smallest, input);
        strcpy(largest, input);
        if (len == 4){
           printf("\n\nTime to quit\n\n");
        }
    
        for ( ; ; )     {
             printf("Enter word: ");
             read_line(input, LENGTH);
             len = strlen(input);            /*  where do I use 'len' to find */
                                                    /* shortest and longest */
                                                    /* input and print those out ??  */
    
             if (strcmp(input, smallest) < 0)   /*  is this correct code for */
             strcpy(smallest, input);               /* sorting alphabetically  */
             else if (strcmp(input, largest) > 0)
             strcpy(largest, input);
             if (len == 4) break;             /* is this necessary operation */
        }
    
    
         printf("\n\n\nYou input four-letter word\n);
         printf("So time to quit.\n\n");
         printf("Smallest word: %s\n", smallest);
         printf("Largest word: %s\n", largest);
    
         return 0;
    }
     
    
    int read_line(char str[], int n)
    {
       char ch;
       int i = 0;
    
       while ((ch = getchar()) != '\n')
           if (i < n)
           str[i++] = ch;
       
          str[i] = '\0';
          return i;  
    }

  2. #2
    Registered User
    Join Date
    Aug 2001
    Posts
    247
    Hi the program is not really very efficient unless it is a class project, as it only allows words up to 3 characters. Still if this is what you require...who am I to say otherwise.

    Here are a few alterations
    Code:
    /*you dont need to return a value from function*/
    void read_line(char str[]);  /*and you dont need LENGTH*/
    
    main()
    {
      /*intialise variable with largest lexicographical combination*/
      /*so it will change*/
        char largest[LENGTH] = "z"; /*lower z*/
         /*same here*/
        char smallest[LENGTH] = "zzz";   
        char input[LENGTH];
        int len;
    
    printf("Enter word: ");
        read_line(input);
        len = strlen(input); 
    /*you could lose the if statement and for loop with a while loop*/
    
       while(len < 4)
       {
             if (strcmp(input, smallest) < 0) 
            /*strcpy here will replace the smallest if lexicographically*/
            /*smaller than stored value in smallest*/  
             strcpy(smallest, input);               
             else if (strcmp(input, largest) > 0)
            /*strcpy here will replace the larger if lexicographically*/
            /*larger than stored value in largest*/  
             strcpy(largest, input);
             printf("Enter word: ");
             read_line(input);
             len = strlen(input);            
        }
    
        /*syntax error in this printf fnct missing "    */
         printf("\n\n\nYou input four-letter word\n);
         printf("So time to quit.\n\n");
         printf("Smallest word: %s\n", smallest);
         printf("Largest word: %s\n", largest);
    
         return 0;
    }
     
    
    void read_line(char str[])
    {
       char ch;
       int i = 0;
    
       while ((ch = getchar()) != '\n')
           if (i < LENGTH)  /*LENGTH global when #define*/
           str[i++] = ch;
       
          str[i] = '\0'; /*no return value*/
    }
    This may save you from reposting...as I said the program is not challenging when only 3 chars can be input....The following allows the user to input any sentance up to 80 chars and sorts longest and shortest then sorts alphabetically (lexicographically) when sentances are of same length...
    Code:
    #include <stdio.h>
    #include <string.h>
    #define MAX 80
    
    void main ()
    {
      char in_string[MAX],
             small[MAX],
             big[MAX]="z"; /*initialise big string so it will change*/
       int i;
      /*initialise small string so it will change*/
      for(i = 0; i < MAX - 1; i++)
           small[i]= 'z';
      small[i]='\0';
    
      printf("\n\tEnter a sentance - Hit return to quit\n\t");
      gets(in_string);
      while(*in_string)
      {
         fflush(stdin);
         if(strlen(in_string)< strlen(small))
             strcpy(small, in_string);
         else if(strlen(in_string)== strlen(small))
    	if(strcmp(small, in_string)< 0)
    	   strcpy(small, in_string);
    
          if(strlen(in_string)> strlen(big))
               strcpy(big, in_string);
          else if(strlen(in_string)== strlen(big))
    	if(strcmp(big, in_string)> 0)
    	     strcpy(big, in_string);
    
       printf("\n\tEnter a sentance - Hit return to quit\n\t");
       gets(in_string);
      }
    
      printf("\n\tSmallest Sentance is \n\t\"%s\"", small);
      printf("\n\tLargest Sentance is \n\t\"%s\"", big);
    }
    Last edited by bigtamscot; 09-29-2001 at 11:12 AM.
    hoping to be certified (programming in c)
    here's the news - I'm officially certified.

  3. #3
    Unregistered
    Guest
    bigtamscot:

    the program is to let user input up to a 20 character word; and any 4-letterword is to stop program (but program still takes that word into account in case it is the shortest) however 2 and 3-letter words as well as 5-20 letterwords are allowed.

    also your second suggestion includes fflush and stdin which we have not discussed in class as of yet, so I don't want to use them


    thanks for the help, though


    bornintheUSA

  4. #4
    Unregistered
    Guest
    ok user is supposed to input any list of words up to length 20 char
    if string = 4 characters, program stops

    the program is supposed to choose as "smallest" word that which comes lexicongraphically first and as "largest" word that which comes last

    MY PROGRAM IS NOT WORKING


    here's output I get with following input:

    Enter word: happy
    Enter word: dunno
    Enter word: zebra /* should be largest */
    Enter word: cat /* should be smallest */
    Enter word: duck



    You input four-letter word
    So time to quit.

    Smallest word: cat
    Largest word: ’¾ūČ /* what the heck is this ??? */


    Code:
    
    #include <stdio.h>
    #include <string.h>
    
    #define LENGTH 20
    
    int read_line(char str[], int n);
    
    main()
    {
        char largest[LENGTH];
        char smallest[LENGTH];
        char input[LENGTH];
        int len;
    
    printf("Enter word: ");
        read_line(input,LENGTH);
        len = strlen(input);
    
       while(len != 4)
       {
             if (strcmp(input, smallest) < 0)
               strcpy(smallest, input);
             else if (strcmp(input, largest) > 0)
               strcpy(largest, input);
             printf("Enter word: ");
             read_line(input,LENGTH);
             len = strlen(input);
        }
    
       if (len == 4)  {
         printf("\n\n\nYou input four-letter word\n");
         printf("So time to quit.\n\n");
       }
    
         printf("Smallest word: %s\n", smallest);
         printf("Largest word: %s\n", largest);
    
         return 0;
    }
    
    
    int read_line(char str[], int n)   /* this is proper code as instructed */
    {
       char ch;
       int i = 0;
    
       while ((ch = getchar()) != '\n')
           if (i < n)
           str[i++] = ch;
    
          str[i] = '\0';
          return i;
    }


    please help me with the output problem !!!

  5. #5
    Unregistered
    Guest
    Salem:

    ok got the initializing handled;

    just a quick question left:

    Is there a better way to do the
    comparison of the length of the word so I don't have to
    have the strcmp after the while loop (at the end of which it checks if the string length is 4) ?????

    Seems repetitive as it is....

    Code:
    
    #include <stdio.h>
    #include <string.h>
    
    #define LENGTH 20
    
    int read_line(char str[], int n);
    
    main()
    {
        char largest[LENGTH];
        char smallest[LENGTH];
        char input[LENGTH];
        int len;
    
        printf("Enter word: ");
        read_line(input,LENGTH);
        len = strlen(input);
        strcpy(smallest,input);
        strcpy(largest,input);
    
       while(len != 4)
       {
             if (strcmp(input, smallest) < 0)
               strcpy(smallest, input);
             if (strcmp(input, largest) > 0)
               strcpy(largest, input);
             printf("Enter word: ");
             read_line(input,LENGTH);
             len = strlen(input);
             if (len == 4)
                  break;
        }
    
         if (strcmp(input,smallest) < 0)   /* :( seems repetitive  here */
            strcpy(smallest, input);
         if (strcmp(input, largest) > 0)
            strcpy(largest, input);
         printf("\n\n\nYou input four-letter word\n");
         printf("So time to quit.\n\n");
    
    
         printf("Smallest word: %s\n", smallest);
         printf("Largest word: %s\n", largest);
    
         return 0;
    }
    
    
    int read_line(char str[], int n)
    {
       char ch;
       int i = 0;
    
       while ((ch = getchar()) != '\n')
           if (i < n)
           str[i++] = ch;
    
          str[i] = '\0';
          return i;
    }

  6. #6
    Unregistered
    Guest

    THAT'LL WORK



    Thanks Salem !!!

    works like a charm and looks so much more concise.

  7. #7
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    #include <string.h>
    #define LENGTH 39




    main()
    {
    char largest[LENGTH];
    char smallest[LENGTH]; /* is the size of array okay */
    char input[LENGTH];
    char inputwo[LENGTH];

    do{
    printf("Enter word: ");
    //_read_line(input, LENGTH);//<--why intercept data here?Erase.
    fgets(input,in,stdin);
    if(!strcmp(input,"Q") )
    return 0;
    if(strlen(input))=4)
    printf("Found a four letter word: %s.",input);getch();
    printf("Enter another word: ");
    fgets(inputwo,in,stdin);
    if(!strcmp(inputwo,"Q") )
    return 0;
    if(strlen(inputwo))=4)
    printf("Found a four letter word: %s.");getch();
    if(strlen(input))<strlen(inputwo)
    strcpy(smallest,input);
    strcpy(largest,inputwo);
    else
    strcpy(largest,input);
    strcpy(smallest,inputwo);
    printf("n\nSmallist is %s",smallest);
    printf("\n\nlargest is %s\n\n",largest);
    }(while !strcmp(inputwo,"Q") )
    return 0;
    }
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  8. #8
    Unregistered
    Guest

    not using fgets or stdin yet in class

    thanks Sebastiani,
    but I got it working.
    I haven't learned yet some of the functions you suggest
    but will keep in mind later when I do, to see how it affects
    input and output (I/O)


    later !!!

Popular pages Recent additions subscribe to a feed