Rearranging a string... and a glitch
Here's what I want it to do:
the left column represents the new string being assigned, the right is the source, before the digits are rearranged (that would work only if it was 15 characters long):
Code:
sOutput Value
sOutput[x] sInput[x]
0 1
1 3
2 5
3 7
4 9
5 11
6 13
7 15
8 0
9 2
10 4
11 6
12 8
13 10
14 12
15 14
For example: sOutput[1] has the same value as sInput[3]... My method for doing this is as follows:
Code:
void scramble()
{
char sInput[1024];
char sOutput[1024];
int iLength = 0;
int i = 0, x = 0, y = 0, z = 0;
cout << "What message do you want to scramble?\n";
cin.get (sInput, 1024);
cin.ignore(1024, '\n');
iLength = strlen( sInput);
strrev(sInput);
x = 1;
for (i = 0; (i<iLength) && (sInput[x] != '\0'); i++)
{
sOutput[i] = sInput[x];
x = x + 2;
}
x = 0;
for (i; (i<iLength) && (sInput[x] != '\0'); i++)
{
sOutput[i] = sInput[x];
x = x + 2;
}
sOutput[i] = '\0';
cout << sOutput << endl << endl;
// 1 2 3 4 5 is an input example
// 1 3 5 2 4 is the scrambled example
// 4 2 5 3 1 is what it looks like after strrev
}
All that works fine... unless you input a string at least 10 characters (0123456789 won't work, but 123456789 will.)
If you input 10 or more characters, it gives you mostly garbage characters.
Also, I can't think of a simple way to descramble that so that 42531 becomes 13524 (strrev would work for that part), but then I need 13524 to be able to become 12345... so it would work both ways.
I contest that this code is more optimized!
[indignant]
harumph (:))
[/indignant]
I finally got my code to work. Just uncomment out the lines that are commented to add back in the functionality that i don't have, if they are needed.
Code:
#include <iostream>
#include <conio.h> // getche();
int main(int argc, char *argv[])
{
char sInput[1024];
int iLength = 0;
int i = 0, x = 0, y = 0, z = 0;
cout << "What message do you want to scramble?\n";
cin.get(sInput, 1024);
//cin.ignore(1024, '\n'); // Do you really need this?
iLength = strlen(sInput);
int half = iLength/2;
//strrev(sInput); // I don't have this function, sorry.
char *sOutput = new char[iLength];
for(int p=0;p<iLength;p++)sOutput[p]='-';
sOutput[iLength]='\0';
for (i=0, x=0; (i<iLength) && (sInput[x] != '\0'); i++, x=i/2){
if (i%2==0){
sOutput[half+x]=sInput[i];
} else {
sOutput[x]=sInput[i];
}
}
cout << "Scrambled: " << sOutput << endl;
for (i=0, x=0; (i<iLength) && (sInput[x] != '\0'); i++, x=i/2){
if (i%2==0){
sInput[i]=sOutput[half+x];
} else {
sInput[i]=sOutput[x];
}
}
cout << "Descrambled: " << sInput << endl;
if (getche());
return 0;
}
~Inquirer