1

The string entered by the user appears to be reversed but it is also followed by a bunch of garbage chars. Here is my reverse function:

void reverse(char str[])
{
    char reversed[MAX_CHAR];

    for(int i = 0; i < strlen(str); i++)
    {
        reversed[i] = str[strlen(str) - i - 1];
    }

    cout << reversed << endl;
}
chillpenguin
  • 2,989
  • 2
  • 15
  • 18

2 Answers2

4

You need to end your string with the NULL character '\0', ASCII value 0.

Try this:

void reverse(char str[]) {
  char reversed[MAX_CHAR];
  int len = strlen(str);

  for(int i = 0; i < len; i++) {
    reversed[i] = str[len - i - 1];
  }

  reversed[len] = '\0'; // Add this

  cout << reversed << endl;
}

This is how C and C++ know where the end of the string is.

Read more about Null-terminated character sequences:

Aiias
  • 4,683
  • 1
  • 18
  • 34
  • That is exactly what i needed thanks! The funny thing is i thought i tried that but i typed '\n' instead of '\0' because i thought you were supposed to end the string with a newline char instead of the NULL char. Thanks for your help! – chillpenguin Apr 08 '13 at 03:28
  • @chillpenguin - No problem. Yeah this can be confusing when you compare it to reading input with something like [`getline()`](http://www.cplusplus.com/reference/string/string/getline/) where it reads up until the new line. – Aiias Apr 08 '13 at 03:30
0

you can solve this in 2 ways either by a) initializing reversed array with null chars

char reversed[MAX_CHAR] = {0};

b) adding null character by end of the reversed string.

reversed[strlen(str)] = '\0';
shivakumar
  • 3,297
  • 19
  • 28