moe moe - 1 month ago 6
C++ Question

How do I create and add a value to a variable from a file

I have a .dat file that looks like this

x -3
r 6
t -2
a 4
w 65
u 83
l 1
m 8888


From this file I am trying to create and then assign a value to the variable using infile. For example,
int x = -3
. I can read in all the values but my problem is how to do what I want after I've read them in.

infile.open("test.dat");

while (infile.peek() != EOF) {
//infile >> check; //gets string from file
//cout << check;
getline(infile,check);
//cout << check << endl;
}


From here would I use a stack and then pop them later?

Answer

Have you tried something like the following?

int value, x;
char variable;

infile.open("test.dat");

while (infile.peek() != EOF) {
    infile >> variable; // get variable
    infile >> value; // get value

    switch(variable){
        case 'x':
            x = value;
            break;
        default:
            cout << "Unknown variable." << endl;
            break;
    }
}

Edit: Based on UKMonkey and Infixed suggestions, you could also just store the values in a map.

map<char, int> variables;

while (infile.peek() != EOF) {
    infile >> variable; // get variable
    infile >> value; // get value

    variables[variable] = value;
}

You can output the values from the map.

for(auto itr : variables){
    cout << itr.first << " : " << itr.second << endl;
}

or something like

cout << variables['x'] << endl;