Search code examples
c++reversecstring

I am getting a bunch of extra chars when i try to reverse a cstring in c++


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;
}

Solution

  • 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: