c++ - std::map not storing any values -
i have following code:
datahandler::datahandler(){ //just call constructor default file. datahandler(default_file); } datahandler::datahandler(const char* filename){ refreshfromfile(filename); } void datahandler::refresh(){ refreshfromfile(default_file); } void datahandler::refreshfromfile(const char* filename){ std::string line, key, value; std::ifstream file(filename); if(file.is_open()){ while(std::getline(file, line)){ key = base64decode(line.substr(0, line.find(" "))); value = base64decode(line.substr(line.find(" ")+1)); float floatvalue = atof(value.c_str()); values[std::string(key)] = floatvalue; std::cout << "values[\"" << key << "\"] = " << values[key] << std::endl; } } file.close(); } float datahandler::operator[](std::string index){ if(values.find(index) == values.end()){ fprintf(stderr, "error: value %s not found, returning 0.0 \n", index.c_str()); return 0.0f; }else{ return values[index]; } } this works neatly, , following debug messages:
values["drive_speed"] = 1 values["grab_wheel_speed"] = 0.2 values["grab_wheel_turbo_speed"] = 0.6 if try size of map, returns 3.
but when try index anything, not found message.
#include "datahandler.hpp" #include <iostream> int main(int argc, const char * argv[]) { datahandler data; data.debug(); std::cout << data["drive_speed"] << std::endl; return 0; } what wrong code?
datahandler::datahandler(){ //just call constructor default file. datahandler(default_file); } this code doesn't think does. doesn't delegate constructor call (as in java, iirr). instead, creates temporary datahandler initialised default_file, destroyed again. "correct" debug output see comes temporary.
to solve this, drop default constructor , change single-parameter 1 this:
datahandler::datahandler(const char* filename = default_file) { refreshfromfile(filename); }
Comments
Post a Comment