I'm trying to write a function that will shift letters in a string a given number of spaces to the left, moving letters that fall off the end to the front. In main the user puts in a command 'Lx' where 'x' is the number of spaces to shift. My problem is that the loop I have set up to move through the steps of the shift doesn't seem to be iterating. At All. It just prints out the user input unchanged. Here's my code:
void ShiftLeft (char user_string[], int length, char shiftL_string[], std::string command)
{
string number; //string after first character is erased
int offSet; //number chars converted via atoi
command.erase(0); //erase 'l'
offSet = atoi (command.c_str()); //convert number into int
int i; //initiate i
//loops the for loop the number of times in offSet
while(i < offSet)
{
i++; //increment i
//following code moves first character to the end of the string
char tmp; //tempmrarily holds char being swapped
tmp = user_string[0]; //make first character equal to tmp
user_string[0] = user_string[length]; //make first character equal to last
user_string[length] = tmp;//make last character equal to temp
int x;//initiat x
//loops through chars of user string. Shifts characters to the left
for (x = 0; x < offSet; x++)
{
cout << "Lx For loop" << endl;
//shifts chars in string to the left
tmp = user_string[x]; //makes char x equal to tmp
//makes char x equal to the next char in array
user_string[x] = user_string[x+1];
user_string[x+1] = tmp;
}
cout << user_string << endl;
}
}
I'm trying to get offSet (the number of spaces to shift) by erasing the first letter in the command string, and converting the leftover number into a int using atoi, setting that to the variable int offSet. Then I'm trying to use offSet at the number of times the shift loop iterates.
Then if you are shifting left you would take the offset amount of characters from the front and move them to the end. If it was a shift to the right you would take the offset amount of characters from the end and move them to the front. Kind of like prepend/appending.
Here is one method that takes advantage of iterators.