lundi 28 décembre 2020

Using a class/struct member delared inside 'if' conditional outside

I am attempting to recreate some "R" scripts in C++, just for the fun of it. Have used C decades ago but not recently. Now what I have is a bit of code where I am reading data from a binary file and placing the data into a structure (or class) with an unknown number of array structures (for the file reading side). Not knowing exactly how many arrays are needed, I define the number after reading another binary file which contains that data. So, I have two options; one to enter new data (which saves that plus the number of arrays to two files); another to read saved data back in (which provides the number of needed array structures). Having done either option via 'IF' conditionals, I need the new or recovered data to perform math on outside those conditionals. This is where things go wrong. The data is not available. The simple example recreates the problem and I have not stumbled upon the solution yet. I am not familiar enough with C++ to find what is most likely something simple to fix. The 'closed' function's first line outside the 'if' conditionals does work as expected, but that's not the data I need, and I don't want that line in the program.

#include <iostream>
using namespace std;
void closed(void);
class traverse {
public:
    int sta;
};
int main()
{
    closed();
    return 0;
}
void closed(void)
{
    traverse stations[1]; // removes 'stations was not declared' error on line 35.
    cout << "Enter 1 or 2\nSelect: ";
    int selType;
    cin >> selType;
    if (selType == 2) {
        cout << selType << " selected\n";
        traverse stations[1];
        stations[0].sta = 2; //need this member value available outside conditional.
        cout << "Value is " << stations[0].sta << " inside." << endl;
    } else {
        cout << selType << " selected\n";
        traverse stations[1];
        stations[0].sta = 1; //need this member value available outside conditional.
        cout << "Value is " << stations[0].sta << " inside." << endl;
    }
    cout << "Value is " << stations[0].sta << " outside." << endl;
}

I originally used a 'struct' but decided to try a 'class' to discover the differences. But, the same problem persists with both, so I don't think it is anything with the definitions, but perhaps with different declarations. Any ideas would be greatly appreciated. Thanks.

Aucun commentaire:

Enregistrer un commentaire