Hi everybody,

I am learning C at the University, and I want to study by myself to avoid difficulties there, I am doing some exercises from a pdf that I got, and it asks me to write a program to invert a string using only what was explained in the pdf, here is my code:

#include <stdio.h>

int main ()
{
        int i, j;
        char string1[50];
        char stringInvertida[50];

        printf("Digite uma frase: ");

        gets(string1);

        for (i=0; string1[i] != '\0'; i++)
        {

                if (i>0) {

                        for (j=i; j>0; j--) {

                                stringInvertida[j] = stringInvertida[j - 1];
                        }

                        stringInvertida[0] = string1[i];

                } else {

                        stringInvertida[i] = string1[i];
                }


        }

        printf("%s\n", stringInvertida);

        return(0);

}

It is working, but if I enter a string smaller than 5 digits, it returns something strange, for example, that's the output of some strings:

Digite uma frase: abc
cba_?

Digite uma frase: abcd
dcba?

Digite uma frase: abcde
edcba

Why are these characters appearing?

Regards =)

initialize the values of your strings like so

char string1[50] = "";
char stringInvertida[50] = "";

then use fgets in receiving a input instead of using gets
here's the reason why

Edited 4 Years Ago by zeroliken: n/a

This article has been dead for over six months. Start a new discussion instead.