Variable value is outside the compiled program

Dear all. I need to have something like the input file, where I could change some variable value, and run the program. There are a lot of variables, and it would take a lot of time to write a code, where program reads values, and defines them to some variables. Therefore I am wondering if there some procedure, to have some file, outside the compiled program, where I define some values, and when the program is executed, the values are redefined according to written in the file. It would be especially nice to have something like header file with defined global variables.
Thank you.
1
2
ifstream fileInput("somefile");
fileInput >> someVariable;
Thanks, but the question was not about simple file reading. Let me explain more clearly. If there is a way to have a file, which looks similar to this:

input.read
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//some explanatory text on variable1
variable1=1;
//some explanatory text on variable2
variable2=2;
//some explanatory text on variable3
variable3=3;
//some very long explanation 
//on
//variable4 meaning in program
variable4=4;
variable5=5;
.
.
.
.
variable100=100;


and when program starts, it assigns variables with values written. Very similar to having a header with global variables which can be edited without the need of recompiling. If to use standard "input/output with files" procedures, it will take a lot of time and lots of lines coding, also not easy input. In case if you would like to add variable, or enlarge explanation you will have to change the program itself.

So, is there a way to do it? Or not?
It can't been in a source/header file as those are compiled, so you are pretty much forced to use an external file as that is really the only way to get data.
You may want to consider simplifying the format or using INI with an existing library.

Can't test right now, but I wrote this based on your current input.read specification:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
std::map<std::string, int> Variables;
std::ifstream in ("input.read");
for(;;)
{
    std::string line;
    std::getline(in, line);
    if(!in) break;
    //trim leading whitespace:
    while(line.size() && (line[0] == ' ' || line[0] == '\t')) line = line.substr(1);
    if(!line.size()) continue; //ignore blank lines
    if(line.size() >= 2 && line.substr(0, 2) == "//") continue; //ignore comments
    std::string varname = line.substr(0, line.find('='));
    line = line.substr(varname.size()+1);
    std::istringstream is (line.substr(0, line.find(';')));
    is >> Variables[varname]; //extract & set the integer
}
I'd not recommend using this code...
Last edited on
Topic archived. No new replies allowed.