Search code examples
c++infinite-loop

My program loops forever and does only a half of what I told it to do


I'm new to programming and I started to make my own Fire Emblem level up calculator, but for some reason it loops infinitely. I can't find an answer. Could you look for any mistakes in my code, please?

#include<iostream>
#include<cstdlib>
#include<windows.h>
int main () {
using std::cout;
using std::cin;
using std::endl;
int level ,str , skl, lck, def, res, inc, hp, spd, nr ;
char cha[10];
nr=1;
cout<< "Which character?";
cin>> cha ;
cout<< "You chose" << cha << "." << endl << "What level do you want him/her to be?";
cin>> level ;
        if (cha[6] = 'Dieck' ) {
            hp = 26;
            str = 9;
            skl = 12;
            spd = 10;
            lck = 4;
            def = 6;
            res = 1;
            while (level > 0) {

            if (rand() % 100 < 90) {
                inc=1;
                //cout<< "HP increased by" << inc ;
                hp+1;

        }
            if (rand() % 100 < 40) {
                inc=1;
            //  cout<< "Strenght/Magic increased by" << inc ;
                str+1;  
        }
            if (rand() % 100 < 40) {
                inc=1;
                //cout<< "Skill increased by" << inc ;
                skl+1;  
        }
            if (rand() % 100 < 30) {
                inc=1;
            //  cout<< "Speed increased by" << inc ;
                spd+1;  
        }
            if (rand() % 100 < 35) {
                inc=1;
                //cout<< "Luck increased by" << inc ;
                lck+1;  
        }
            if (rand() % 100 < 20) {
                inc=1;
                //cout<< "Defense increased by" << inc ;
                def+1;  
        }
            if (rand() % 100 < 15) {
                inc=1;
                //cout<< "Resistance increased by" << inc ;
                res+1;

        }
        nr+1;
        level-1;
        //cout<<"NR."<< nr << " New stats (in order) HP/STR/SKL/SPD/LCK/DEF/RES " << hp <<" "<< str <<" "<< skl <<" "<< spd <<" "<< lck <<" "<< def <<" "<< res << endl; 
        Sleep(1);

        }
        cout<< "Stats "<< "HP/STR/SKL/SPD/LCK/DEF/RES " << hp <<" "<< str <<" "<< skl <<" "<< spd <<" "<< lck <<" "<< def <<" "<< res << endl;
        return 0 ;
}

}


Solution

  • One issue you have is cha[6] = 'Dieck'

    cha[6] is a single character such as 'D' or 'i' but not the whole thing. Also = sets cha[6] equal to 'Dieck' which can't happen because 'Dieck' is not a valid character. To compare them you'd need == but you can only compare one character at a time like cha[0] == 'D'

    Really you should make your input a string, and use the compare() method of the string.

    std::string input;
    // stuff
    cin >> input;
    
    if (input.compare("Dieck") == 0)
    {
       // more stuff
    }