Print a string in reverse order using cout

I am stuck on one part of an assignment. Among other things, we have to get a character string of random length from a user and then reverse and output that string. In order to do this, I need to be able to call my string length function inside of my print backwards function, but I cannot figure out how to do it. I cannot change the function definitions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  void GetStringLength(char * c, int * length)
{
  *length = 0;

  for (int i = 0; c[i] != '\0'; ++i)

  *length += 1;  
}

void PrintStringBackwards(char * const c)
{
  GetStringLength(c, &l);
  char swap;
  for (int j = 0, k = *length; j < *length; ++j, --k)
 {
	 swap = c[j];
	 c[j] = c[k];
	 c[k] = swap;
	 std::cout << c[j];
 }  
}
char *c is a pointer to character. It gives you the current character at that particular location of memory. Every string in c++ is terminated by "\0"(null) character. Using char* you can read the characters till you reach "\0". Increment a counter during this process. When you reach the null character you should have the string length in the counter. Hope this helps
Last edited on
Thank you for the response. I have the length of the string, but I cannot get it to reverse. Any ideas?
You need perhaps to access each character in reverse order?
This code gets each character and prints it, does that give you any ideas?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

using namespace std;

int main()
{
    string myString = "THIS IS A TEST STRING";
    for (unsigned int i=0;i<myString.length();i++)
    {
        cout << myString[i];
    }
    cout << endl;
    return 0;
}

Yes! I got it! I was making it way too complicated. Thank you both so much for your replies and assistance.
Topic archived. No new replies allowed.