1

I have written a code to reverse a string

#include < iostream >
#include < cstring >

using namespace std;

string Reversal(char * s);

int main()
{
    char str[25];

    cout << "Enter a Name :";

    cin.get(str, 25);
    cout << "You have entered: " << str;

    cout << "\nReversed : " << Reversal(str);
    return 0;
}

string Reversal(char * s)
{
    int count = strlen(s);
    char temp[count];
    for (int i = 0; i < count; i++)
    {
        temp[i] = * (s + (count - 1) - i);
    }
    return temp;
}

Have referred below link to make cin take whitespaces as input:

How to cin Space in c++?

But the output is showing a few junk characters ? Any suggestion why so? enter image description here

Community
  • 1
  • 1
Gaurav K
  • 2,864
  • 9
  • 39
  • 68

2 Answers2

4

When you implicitly construct a std::string from temp, the latter is expected to be NUL-terminated, which it isn't.

Change

return temp;

to

return std::string(temp, count);

This uses a different constructor, one that takes an explicit character count and doesn't expect temp to be NUL-terminated.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

The last character in the temp array should be null-terminated. Make it 1 longer than the size of your input string. Make the last character the null character ('\0').

string Reversal(char *s)
{
 int count=strlen(s);
 char temp[count+1]; //make your array 1 more than the length of the input string
 for (int i=0;i<count;i++)
 {
   temp[i]= *(s+(count-1)-i);
 }

 temp[count] = '\0'; //null-terminate your array so that the program knows when your string ends
 return temp;
}

The null character specifies the end of the string. Usually it is a byte with all 0 bits. If you don't specify this as the last character of your temp array, the program will not know when is the end of your array of characters. It will keep including every character until it finds a '\0'.

maditya
  • 8,626
  • 2
  • 28
  • 28