It's possible to split the strings into arrays.
The way to do that depends on what you want to obtain.
Regarding the repeats, you need to store separately the lines so repeating them will be easy. I'd suggest using a vector.
1 2 3 4 5 6 7 8 9 10
|
std::string currentline;
std::vector<std::string> cmdlist;
if (myfile.is_open())
{
while ( getline(myfile,currentline) )
{
cmdlist.push_back( currentline + '\n' );
}
myfile.close();
}
|
Generating the repeated command can be done using only loops.
The idea is to start from the end.
- create an empty string that will contain the repeated commands
- loop from the last command to the first
-- append current command to the beginning of your string
-- concatenate your string with itself the required number of times
Using your example REPEAT 10[LEFT 90 REPEAT 20[FORWARD 5 REPEAT 10[LEFT 90 FORWARD 10]]]:
- First iteration, append third command "LEFT 90 FORWARD 10" to the string. Since it was empty now it contains "LEFT 90 FORWARD 10".
- Concatenate the string 9 (10-1) times. It contains 10x"LEFT 90 FORWARD 10"
- Second iteration, append second command "FORWARD 5". The string contains
"FORWARD 5" + 10x"LEFT 90 FORWARD 10"
- Concatenate. The string contains 20x("FORWARD 5" + 10x"LEFT 90 FORWARD 10")
- Third iteration, append first command "LEFT 90". The string contains
"LEFT 90" + 20x("FORWARD 5" + 10x"LEFT 90 FORWARD 10").
- Concatenate. The string contains
10x("LEFT 90" + 20x("FORWARD 5" + 10x"LEFT 90 FORWARD 10"))
The code would be something like that:
1 2 3 4 5 6 7 8 9 10 11
|
void RepeatCommands( const std::vector<int>& nRepeats, const std::vector<std::string>& Cmds, std::string& Result )
{
Result.clear(); // to make sure it's empty
unsigned int nCmds = Cmds.size();
for( unsigned int i = nCmds-1; i >= 0; --i )
{
AppendLeft( Cmds[i], Result ); // append current command at the left of "Result"
Repeat( Result, nRepeats[i] ); // concatenate Result to itself the desired number of times
}
}
|
I voluntarily used function calls so that you can understand the big steps and not focus on pointless implementation details.
In your case, these functions could be written
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void AppendLeft( const std::string& LeftPart, std::string& RightPart )
{
RightPart = LeftPart + RightPart; // string concatenation
}
void Repeat( std::string& mystring, const unsigned int N )
{
// this function modifies "mystring" so that it contains N repeats of itself
// it's a very inefficient implementation
std::string tmp = mystring;
for( unsigned int i = 0; i < N-1; ++i )
mystring += tmp;
}
|