-
Hmmm, I was trying to use the i's to try and fix the copying over problem and I guess I never got a chance to clean up the code a little. Here, how's this:
Code:
#include <iostream>
#include <cstring>
using namespace std;
void stringReverser(char* array, int len);
int main()
{
char array[50];
cout<<"Please enter a string to have it reversed: ";
cin.get(array,49);
int length = strlen(array);
stringReverser(array,length);
cout<<"Your string reversed is: "<<array<<endl;
system("PAUSE");
return 0;
}
void stringReverser(char* array, int len)
{
char newArray[50];
int j = len-1;
for(int i = 0;i<len;i++,j--)
{
newArray[i]=array[j];
}
for(int i = 0;i<len;i++)
{
array[i]=newArray[i];
}
}
-
here's an alternate version based on Salems suggestion:
Code:
void stringReverser(char* array, int len)
{
char ch;
for(int i = 0; i < len/2; ++i)
{
//swap chars in same space without temporary holding array.
ch = array[x];
array[x] = array[len - 1 - x];
array[len - 1 - x] = ch;
}
};
If you are allowed to use standard functions, you could consider using std::swap() from the std::algorithm header instead of the three line swap code in the for loop.