c++ - std::out_of_range on static int variable -


i using static variable make-shift timer in small dos-based game (course project). variable keeps track of number of turns before status effect wears off. here code:

for (auto &i : v) // <-- code calls enemyattack     enemyattack(i, p, str, i.attack); break;  void enemyattack(enemy &e, playerobject &p, std::array<std::string, num_messages> &str, void(*a)(playerobject &p, std::array<std::string, num_messages> &str)) {     int die = rand() % 100 + 1;     int d = 1;      a(p, str); // <-- call function causes error      ... }  void batattack(playerobject &p, std::array<std::string, num_messages> &str) {     static int time = 2;     static bool bit = false;      if (rand() % 10 < chance_of_status_effect && !bit) {         p.damage /= 2;         str[status] += "weakened ";         bit = true;     }     else if (time == 0) {         p.damage *= 2;         str[status].replace(str[status].find("weakened ", 0), 9, "");          time = 2;  // <-- error         bit = false;     }     else if (bit) {         time--;     } } 

i receive std::out_of_range error @ line time = 2; inside second condition. function called via function pointer primary attack function. error seems random , msvs reports variables having value should have when error occurs.

the line

str[status].replace(str[status].find("weakened ", 0), 9, ""); 

is disaster waiting happen. let @ inner find first.

str[status].find("weakened ", 0) 

your using value "weakened " twice in short program when enough have spelling errors, therefore better use named value here there no chance of making mistakes.

constexpr const char *weakenedstr = "weakened "; 

and use

str[status].find(weakenedstr , 0) 

secondly fail, if string not found returns 'npos' (which -1). need test too

auto pos = str[status].find("weakened ", 0); if (pos != std::string::npos)   str[status].replace(pos, 9, ""); 

next '9' magic number, should named value

constexpr const char *weakenedstr = "weakened "; const int weakenedstrlen = strlen(weakenedstr); // strlen sadly not constexpr. 

giving

auto pos = str[status].find("weakened ", 0); if (pos != std::string::npos)   str[status].replace(pos, weakenedstrlen, ""); 

note: untested code, bug occur.


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -