How this could be optimized (if there any need for optimization) and what are your thoughts?
This will be a function that returns a random number from Dice Notation (more on Wikipedia). I will later use this function to determine whether some skill check is passed or not.
#include <string>
using namespace std;
int toInt(string text) {
return atoi(text.c_str());
}
int main(int argc, char* argv[]) {
srand(time(NULL));
string diceString = "1d6+4";
unsigned int dice1number = 0;
string info = "dice ["+diceString+"] = %i\n";
printf("==[START]================\n");
printf(info.c_str(),dice1number);
// parse dice
unsigned int i=0;
unsigned int part = 1;
string dicePart1 = "";
string dicePart2 = "";
string dicePart3 = "";
for(i=0;i<diceString.length();i++) {
if (diceString[i]=='d') {
part = 2;
continue;
}
if (diceString[i]=='+') {
part = 3;
continue;
}
if (diceString[i]=='-') {
dicePart3 += "-";
part = 3;
continue;
}
if (part==1 && diceString[i]>='0' && diceString[i]<='9') {
dicePart1 += diceString[i];
}
if (part==2 && diceString[i]>='0' && diceString[i]<='9') {
dicePart2 += diceString[i];
}
if (part==3 && diceString[i]>='0' && diceString[i]<='9') {
dicePart3 += diceString[i];
}
}
printf("dicePart1 = [%s]\n",dicePart1.c_str());
printf("dicePart2 = [%s]\n",dicePart2.c_str());
printf("dicePart3 = [%s]\n",dicePart3.c_str());
int roll = 0;
int add = toInt(dicePart3);
roll = toInt(dicePart1) * (rand() % toInt(dicePart2)) + add;
printf("roll = [%i]\n",roll);
printf("==[END]==================\n");
return 0;
}