Search code examples
c++variablesstructvisual-studio-2015unhandled-exception

How to use a variable in the same struct it's defined in?


I am making a rogue-like ASCII game and made a struct called "Armor" and I want to use the name variable in the struct to have the path to whatever the name is.

struct Armor {
    bool equipped;
    std::string name;

    int getBuff(int buff) {
        std::fstream item;
        std::string line;
        std::string response;
        std::string value;

        item.open("../Data/Items/" + name + ".item", std::fstream::in);
        if (item.fail())
            errorQuit("ERROR: There was a problem loading armor type .ITEM file."); // Error and quit function

        while (!item.eof()) {
            getline(item, line);
            response = split(line, '=', 0); // Splits string
            if (response == "buff" + std::to_string(buff)) {
                value = split(line, '=', 1);
                break;
            }
        }

        item.close();
        return std::stoi(value);
    }

};

Then I called it like this:

Armor sword;
    sword.name = "Wooden Sword";
    int buff = sword.getBuff(1);

But this throws an Unhandled exception error. I changed it so that getBuff takes 2 parameters, int buff and std::string itemName. and replaced name in the path with itemName; Then I tried calling it like this:

Armor sword;
    sword.name = "Wooden Sword";
    int buff = sword.getBuff(1, sword.name);

But this throws the same error.

I'm confused as to why I can't use the name variable as it has already be defined. Is there any other way I can use the name variable like that?


Solution

  • Thanks for all your help but I figured it out on my own.

    I just made a stupid error that I overlooked like an idiot.

    It is searching for buff + int (e.x. buff1) in the file but there are multiple lines that contain that word so I guessed that messed it up. I just made an adjustment to the if statement and it is working as expected.

    Sorry to bother you!