Help - request user input, then reverse output

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Chavs
    New Member
    • Feb 2008
    • 2

    Help - request user input, then reverse output

    Hello,

    This is my first post, hopefully in the right area. I'm quite new to C++ so dont know advanced techniques, but Im trying to get my head around a task weve been given during a lab at uni.

    This is the code I have so far:
    Code:
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {	
    	char* endPointer;
    	char text[5];
    	char reverse[5];
    	int i;
    
    	cout << "Please enter text - of less than 5 characters: " << endl;
    	cin >> text;
    	cout << "-------------------" << endl;
    	cout << "Straight output: " << endl;
    	cout << text << endl;
    	cout << "-------------------" << endl;
    	
    	cout << "Address output: " << endl;
    	endPointer = text;
    	while(*endPointer != '\0')
    	{
    		cout << *endPointer << " " << (int*)endPointer << endl;
    		endPointer++;
    	}
    	cout << "-------------------" << endl;	
    	
    	endPointer = endPointer -1; // Starts at /0, get back to last letter
    
    	cout << "Reverse output: " << endl;
    	for(i=0;i<5;i++)
    	{
    			cout << *endPointer << endl;
    			endPointer--;
    	}
    	cout << "-------------------" << endl;	
    	return 0;
    }
    I have a couple of questions regarding the code. Firstly, it works fine, but I dont wont the funny shapes coming on the ouput of the reversed text. I believe its because its reached '/0', however that shouldnt be coming up since Ive used endPointer--; surely?

    Secondly, when I enter a 5 character word into it, it executes perfectly, yet I still get an error - "Stack around the variable 'text' was corrupted", which I have no idea how to fix.

    Thanks for your help :)
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Your arrays are too small for a 5 character string.

    Remember, you need a null terminator. So, a 5 character string will need a 6 character array. That's your stack corruption.

    Also, there a a lot of hard-coded 5's in your code. I suggest you use a const int for the array size and use the int in the code instead of the 5. That way, when you need to change to 6, you just need to change the const int and recompile as opposed to scouring the code for 5's to change to 6.

    [code=c]
    const int SIZE = 6;
    char text[SIZE];

    for( int i = 0; i < SIZE; ++i)
    {
    etc...
    [/code]

    Comment

    • Chavs
      New Member
      • Feb 2008
      • 2

      #3
      Thank you for your reply, I understand now where ive gone wrong.

      Thanks again :)

      Comment

      Working...