how to stop my if statement executing more than once

hi I'm currently creating text based game, which involves a character levelling up after he reaches a certain amount of experience. however every time player experience increase after, he levels up. but not at the next experience level. how can I stop this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  void levelup()
{
   int required_xp1 = 200;  //experienced needed to level  up
   int required_xp2 = 500;
   int required_xp3 = 1000;
   int required_xp4 = 1800;
   int required_xp5 = 2800;
   int required_xp6 = 5000;
   int required_xp7 = 8000;
   int required_xp8 = 12000;
   int required_xp9 = 18000;
   int required_xp10 = 25000;
   int required_xp11 = 9999999;
  

  if(xp >= required_xp1){      // IF XP IS HIGH ENOUGH LVL WILL INCREASE 
    lvl=2;                         
    
    SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ),  6);//changes font to gold
    type_text("You leveled up! Congratulations\n\n");
    SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ),  7);// changes it back to default
    
char_stats_increase();}


character stat increase is another function that increases the player stats when he levels up. but after the player has levelled up once he will keep levelling up to lvl2 and his stats will keep increasing.

is there anything I can put in my if statement to make it only happen once then ignore it
Last edited on
Check the lvl variable as well.
1
2
3
4
if (lvl == 1 && xp >= required_xp1)
{
	// level up
}
Yes.

The "exam scores" assignment has a shorter lookup table, but as an example:
1
2
3
4
if ( 90 < score ) return 'A';
else if ( 80 < score ) return 'B';
else if ( 50 < score ) return 'C';
else return 'D';

If score is over 90, it is over 80 and 50 too, but the if..else chain in proper order prevents unnecessary evaluation.
However, this method does not suit to your problem for two reasons.

This does:
if ( level is not yet X && enough exp for level X )
Logical AND.


[edit] Peter's version allows only single level at a time. If character can level more by single deed, then use <.
Last edited on
Thanks for the quick answers guys., can't believe it's such an easy fix. Thanks a lot again. I can be well on my again :)
Topic archived. No new replies allowed.