Gary Wessle <ph****@yahoo.comwrites:
Hi
I have n bool variables in a namespace, I need to write a routine
that sets the value of each according to whats in n corresponding files
named after the variables.
#include <vector>
#include <string>
using namespace std;
void set_switch(bool& swi, const string& f){
ifstream in( f.c_str() );
string line;
getline(in, line);
if( line == "false" )
swi = false;
else
swi = true;
}
int main(){
bool abc, def;
set_switch(abc, "status/abc.txt");
set_switch(def, "status/def.txt");
// ... n times
}
#v+
#define SET_SWITCH(var) set_switch(var, "status/" ##var ".txt")
int main() {
bool abc, def;
SET_SWITCH(abc);
SET_SWITCH(def);
return 0;
}
#v-
That's as far as you can get with a preprocessor I think. The other
method would be:
#v+
int main() {
static const char *file_names[] = { "abc", "def" };
char buffer[128] = "status/";
std::vector<boolvec;
for (unsigned i = 0; i<sizeof file_names / sizeof *file_names; ++i) {
bool tmp;
strncat(buffer, file_names[i], sizeof buffer - 1);
strncat(buffer, ".txt", sizeof buffer - 1);
set_switch(tmp, buffer);
vec.push_back(tmp);
}
return 0;
}
#v-
Or you could use some kind of std::map<string, boolif you want to
have named flags, eg. something like:
#v+
int main() {
static const char *flag_names[] = { "abc", "def" };
char buffer[128] = "status/";
std::map<std::string, boolflags;
for (unsigned i = 0; i<sizeof flag_names / sizeof *flag_names; ++i) {
bool tmp;
strncat(buffer, flag_names[i], sizeof buffer - 1);
strncat(buffer, ".txt", sizeof buffer - 1);
set_switch(tmp, buffer);
flags[std::string(flag_names[i])] = tmp;
}
return 0;
}
#v-
(note that none of the code was tested)
--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl>---<jid:mina86*chrome.pl>--ooO--(_)--Ooo--