Taking input and Outputting it backwards

This is a discussion on Taking input and Outputting it backwards within the C Programming forums, part of the General Programming Boards category; I'm not sure what the problem is here, but I can get the program to produce, "Hello" as "olleH" but ...

  1. #1
    Registered User
    Join Date
    Jun 2003
    Posts
    7

    Taking input and Outputting it backwards

    I'm not sure what the problem is here, but I can get the program to produce, "Hello" as "olleH" but when I type something like,
    "Hello my nick is whtpirate" I only get "olleH" what seems to be the problem ? I would appreciate help thank you

    Code:
    #include <stdio.h>
    
    // Take user input and Output it backwards.
    
    int a;
    char choice[200];
    
    int main()
    {
     // Gotta put my little plug in there as usual :)
     printf("\n Text reverser; Coded by whtpirate(elder(justin)) of LogiTeam.\n");
     puts("\n");
      // Begin Main;
      printf("\tPlease enter a string: ");
       scanf("%199s", choice);
      for (a = strlen(choice) + 1; a != -1; a--) // This should make the text go backwards.
       {
        printf("%c", choice[a]); 
      }
     return 0;
    }

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    The %s format specifier to scanf is whitespace delimited. Have you looked at the FAQ?
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Jun 2003
    Posts
    7
    thanks for the help, works perfectly now

    Code:
    #include <stdio.h>
    
    // Take user input and Output it backwards.
    
    int a;
    char choice[200];
    
    int main()
    {
     // Gotta put my little plug in there as usual :)
     printf("\n Text reverser; Coded by whtpirate(elder(justin)) of LogiTeam.\n");
     puts("\n");
      // Begin Main;
      printf("\tPlease enter a string: ");
       fgets(choice, 200, stdin);
      for (a = strlen(choice) + 1; a != -1; a--) // This should make the text go backwards.
       {
        printf("%c", choice[a]); 
      }
     return 0;
    }

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Actually, your loop has a bug. You assign a with a value that could be outside the bounds of the array. Other thoughts:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
       char buffer[BUFSIZ];
       /*
        * Prompt the user. Ensure that the prompt is displayed.
        */
       fputs("Please enter a string: ", stdout);
       fflush(stdout); /* http://www.eskimo.com/~scs/C-faq/q12.4.html */
       /*
        * Get one line of input.
        * Checking return values is a good habit to have.
        */
       if ( fgets(buffer, sizeof(buffer), stdin) != NULL )
       {
          size_t i; /* strlen() returns a size_t */
          /*
           * Look for a newline ('\n') in the input string.
           * If found, replace it with a terminating null character ('\0').
           */
          char *ch = strchr(buffer, '\n');
          if ( ch != NULL )
          {
             *ch = '\0';
          }
          /*
           * Set the index to the end of the string.
           *
           * If we had a 3-character string "abc", strlen() would return 3.
           * This would mean that buffer[0] == 'a', buffer[1] == 'b',
           * buffer[2] == 'c', and buffer[3] == '\0' (the null termination).
           *
           * So we subtract 1 from strlen(buffer) so that buffer[i] is the
           * last character immediately preceding the null termination.
           */
          i = strlen(buffer) - 1;
          do
          {
             putchar(buffer[i]);
          } while ( i-- > 0 ); /* we want to print until buffer[0] and then stop */
          /*
           * It is a good idea to make sure programs that output to the stdout
           * finish with a newline.
           */
          putchar('\n');
       }
       return 0;
    }
    
    /* my output
    Please enter a string: Hello my nick is whtpirate
    etaripthw si kcin ym olleH
    */
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  5. #5
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    #include <stdio.h>
    void p( void )
    {
        int c = fgetc( stdin );
        if( c == '\n' )
            return;
        p( );
        fputc( c, stdout );
    }
    int main ( void )
    {
        printf("Enter a string:\n");
        p();
        return 0;
    }
    I'm partial to this method myself.

    Quzah.
    Hope is the first step on the road to disappointment.

  6. #6
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,157
    Cute quzah!!

    Actually, Dave, your loop has a problem too. And a suggestion.

    1) the suggestion:
    /*
    * Look for a newline ('\n') in the input string.
    * If found, replace it with a terminating null character ('\0').
    */
    char *ch = strchr(buffer, '\n');
    . . .
    i = strlen(buffer) - 1;
    Why use the overhead of strchr()? Move the strlen() above and the '\n', if it exists, will be at buffer[i]. Just check it directly.

    2) the problem:
    * So we subtract 1 from strlen(buffer) so that buffer[i] is the
    * last character immediately preceding the null termination.
    */
    i = strlen(buffer) - 1;
    do
    {
    putchar(buffer[i]);
    } while ( i-- > 0 );
    If just RETURN was pressed, this will process buffer[-1], which is not a good thing. In this case a while loop would be safer.
    Code:
    i = strlen(buffer) - 1;    /* get end of string */
    while (i >= 0)             /* while there's still string left */
    {
        putchar(buffer[i--]);  /* output char, dec i */
    }
    === or ===
    i = strlen(buffer);        /* get str length */
    while (i)                  /* while not a start of string */
    {
        putchar(buffer[--i]);  /* dec i and display the character */
    }
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  7. #7
    Banned
    Join Date
    May 2003
    Posts
    124
    Very good code quzah!!

  8. #8
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,652
    Code:
    void p( void )
    {
        int c = fgetc( stdin );
        if( c == '\n' )
            return;
        p( );         // where do we go from here?
        fputc( c, stdout );
    }
    
    // maybe
    
    char * strtail(const char * data)
    {
     char * ptr  = (char*)data;
     while(*ptr) ptr++;
     return ptr;
    }
    
    
    char * strev(char * buffer, const char * data)
    {
     char * end = strtail(data), * ptr = buffer;
     while(end != data)   *(ptr++) = *(--end);
     *ptr = 0;
     return buffer; 
    }
    
    char * strevget(char * buffer, int length)
    {
     return strev(fgets(buffer, length, stdin));
    }

  9. #9
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Originally posted by WaltP
    Actually, Dave, your loop has a problem too. And a suggestion.

    1) the suggestion:Why use the overhead of strchr()? Move the strlen() above and the '\n', if it exists, will be at buffer[i]. Just check it directly.
    That works for me. I was just putting some of the suggested FAQ code into the example.
    Originally posted by WaltP
    2) the problem: If just RETURN was pressed, this will process buffer[-1], which is not a good thing. In this case a while loop would be safer.
    D'oh! I hate it when I miss stuff like that.
    Originally posted by WaltP
    Code:
    i = strlen(buffer) - 1;    /* get end of string */
    while (i >= 0)             /* while there's still string left */
    {
        putchar(buffer[i--]);  /* output char, dec i */
    }
    When is a size_t not greater than or equal to 0? I think prefer the second option.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
       char buffer[BUFSIZ];
       fputs("Please enter a string: ", stdout);
       fflush(stdout);
       if ( fgets(buffer, sizeof(buffer), stdin) != NULL )
       {
          size_t i = strlen(buffer);
          if ( i > 0 )
          {
             if ( buffer[i - 1] == '\n' )
             {
                --i;
             }
             while ( i-- > 0 )
             {
                putchar(buffer[i]);
             }
             putchar('\n');
          }
       }
       return 0;
    }
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  10. #10
    Registered User
    Join Date
    Jun 2003
    Posts
    14
    I did not get a chance to read through all of the postings,
    I am running out.

    However I did see one immediate problems with your code,
    which is:

    1. No inclusion of <string.h> for the usage of the
    strlen() function
    #include <string.h>

    Added Suggestions

    Wen using the puts() function, it is not necessary
    to add the newline escape sequence \n within the
    puts() function ... unless your intent was to
    have two newline characters. You could simply
    use puts("");

    I see that you want to ALWAYS pump your credits in your
    output of your code ... that's perfectly normal ...
    however, you might want to create a function such as

    void whtpirate(); /* whtpirate function prototyp */
    void whtpirate()
    {
    printf("\n Text reverser; Coded by whtpirate(elder(justin)) of LogiTeam.\n");
    };

    If you create the function out of the main() function
    you could call the whtpirate() from any other funtion
    that you might create.

    I hope that my suggestions and correction help you.

    I wish you the best in your coding.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 17
    Last Post: 07-14-2009, 08:17 AM
  2. Hash Table outputting incorrect number
    By Paul Skinner in forum C Programming
    Replies: 4
    Last Post: 11-20-2008, 05:19 AM
  3. Taking input in C
    By GUIPenguin in forum C Programming
    Replies: 1
    Last Post: 04-12-2006, 01:53 PM
  4. Looping when outputting to a file
    By nizbit in forum C Programming
    Replies: 4
    Last Post: 03-05-2005, 09:26 AM
  5. Outputting to a File Modified Text
    By alpha in forum C++ Programming
    Replies: 8
    Last Post: 11-24-2003, 07:39 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21