Reverse String - Odd characters showing up from mem address?

This is basically what the problem looks like:

Enter string to reverse: AMAZING
Reversed string: ===============GNIZAMA
Do you want to insert another string (Y/N)?: Y

Enter string to reverse: NEVER
Reversed string: ====================REVENMA
Do you want to insert another string (Y/N)?: N


Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <string.h>
using namespace std;
  
void Reverse(char *str);

int main()
{
    char user_input[40] = "";  
    char new_input[40]; 
    char next_item;

    do
    {
    cout << "Enter string to reverse: ";
    cin.getline(user_input, 40);
    Reverse(user_input);
    cout << "Reversed String: " << new_input << endl;
    cout << "Do you want to insert another string (Y/N)? ";
    cin >> next_item;
    cin.ignore();    
    }

    while (next_item == 'Y' || next_item == 'y');
	

return 0;
}

void Reverse(char *str)  
{                 
    int x = strlen(str);
    for(int y = x; y >= (x/2)+1; y--)
    {
    swap(str[x-y],str[y-1]);
    }


}
Last edited on
Anyone?
It worked just fine for me.
Hmmm, could you possibly tell me what you entered to be reversed? Although I guess it doesn't really matter since I'm still getting the odd characters. Perhaps it might be old data from past debug runs.
Line 18 should be:

cout << "Reversed String: " << user_input << endl ;

And you can get rid of line 10.

Last edited on
Put in AMAZING and NEVER, same as you.
If you are asking why the MA at the end of the 2nd it might be since you use the same char array to store the input without resetting the null? Not sure exactly, to be honest. Honestly, if that was the case I would expect the 2nd output to be AMREVEN.

Edit: Actually, it works fine for me too, after making the change cire suggested. Otherwise it simply output nothing, as you would expect from an empty char array. getline() must add the terminating null to the end of never anyway.
Last edited on
Topic archived. No new replies allowed.