Thread: Read a string and invert it

  1. #1
    INSANE INSIDE ekosix's Avatar
    Join Date
    May 2010
    Location
    Rio de Janeiro, Brazil
    Posts
    44

    Question Read a string and invert it

    I'm trying to do an exercise about for, but it's not working...
    The exercise says: "Make a program that inverts a string: read the string with gets and save it inverted in another string. Use the for command to scan the string up to its end."

    I did this code:
    Code:
    #include <stdio.h>
    int main()
    {
        int i1,i2,t=0;
        char s1[50],s2[50];
        printf("Digite uma string: ");
        gets(s1);
        for(i1=0;s1[i1]!='\0';++i1)
        {
            ++t;
        }
        i1=0;
        for(i2=t;i2>=0;--i2)
        {
            s2[i2]=s1[i1];
            ++i1;
        }
        printf("\n\nA nova string e:\n%s",s2);
        return (0);
    }
    ... but it doesn't work.

    Could anybody, please, check my code and correct it?
    Thanks a lot!

  2. #2
    Registered User
    Join Date
    Aug 2005
    Posts
    266
    its possible that you are not accounting for placing the \0 in the new string?

    when you read a string with gets it automatically adds on a \0

    so if you type in FROG, it saves FROG\0 inside of s1.

    now when you reverse it into s2, you get \0GORF ..when you try to print this it finds the \0 AND STOP PRINTING.

    the \0 exists so that the array knows when to end.

    try starting at t-1 instead of t, and setting s2[t] to '\0'
    Last edited by rodrigorules; 05-11-2010 at 02:08 PM.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need to invert the output!
    By alvifarooq in forum C++ Programming
    Replies: 11
    Last Post: 09-23-2004, 10:46 AM
  2. string inversion
    By Kohatian 3279 in forum C++ Programming
    Replies: 13
    Last Post: 05-01-2002, 03:45 PM

Tags for this Thread