Help with reversing string

i cannot use pointers and i have to ask the user to enter it and store into an array, then replace the content of the string in reverse and save into another array, and finally print the original and reversed string in the function.
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
  void rev_str ()
{
	 
    int x;
	char std[81];
	char revstd[81];
	cout << "please enter a string: ";
	cin  >> std;
	x = sizeof (std);
	for (int i = 0; i < x ; i++)
	{
		std[i] = revstd[i];
		
	}
	for (int j = x - 1; j >= 0; j--)
	{
		cout << std[j];
    
	}

	

}
From http://www.cplusplus.com/faq/sequences/arrays/sizeof-array/
Firstly, the sizeof() operator does not give you the number of elements in an array, it gives you the number of bytes a thing occupies in memory.


And since arrays are static they always have the same size(in your case 81).

Instead you could try iterating over the array until you find the null character ('\0') and that would give you the size you wanted
Have you tried using a stack or are you creating a new string?
Reversing a string can be done in-place:

1
2
3
4
5
6
7
8
9
10
11
12
char mystr[100];
std::cin.getline(mystr, 100);

// http://www.cplusplus.com/reference/istream/istream/gcount/
int len = std::cin.gcount();

for (int i = 0; i < len--; i++) {
    // http://en.cppreference.com/w/cpp/algorithm/swap
    std::swap(mystr[i], mystr[len]);
}

std::cout << mystr << std::endl;

http://ideone.com/oQ7oP7

In your case, the only thing you are missing is the actual reversing process
Last edited on
Topic archived. No new replies allowed.