I'm reading in data from an external file. The data comes in different types, both integers and strings and is shown here:
{
"height":170,
"weight":73,
"country":"UK",
"city":"Sheffield",
"year":2017,
"month":7,
"day": 2
}
I'd like to decide manually which fields to read without having to recompile the program. Therefore, I do this by listing in a text file which fields I am interested in. I have a file for integer-variables and one for strings:
ints.txt
weight
year
month
strings.txt
country
Now, the data I read I store in an object of class Read_Data
(see code below). I keep the data in maps
, one for integers and one for strings. I'd like to know where/how can improve on my program and make it more professional. I have myself been thinking if it is possible to merge the integer- and string map such that I don't have to treat them individually as I do currently.
Here is the complete code (and a link to nlohmann's json reader):
main.cpp
#include <iostream>
#include "data.h"
int main()
{
///create object to store data
Read_Data read_data;
///read data from file
read_data.read();
return 0;
}
data.h
#ifndef SFE_H
#define SFE_H
#include <fstream>
#include "json.hpp"
class Read_Data
{
private:
///maps of the read variables
std::map<std::string, int> int_map;
std::map<std::string, std::string> string_map;
///vectors of which variables to read
std::vector<std::string> int_list;
std::vector<std::string> string_list;
public:
Read_Data();
int read_list(std::string file_name, std::vector<std::string> &list);
void read();
};
#endif
data.cpp
#include "data.h"
///which variables we want to read
Read_Data::Read_Data()
{
read_list("ints.txt", int_list);
read_list("strings.txt", string_list);
}
int Read_Data::read_list(std::string file_name, std::vector<std::string> &list)
{
std::string value;
std::ifstream file_strm(file_name);
if (file_strm.is_open())
{
while (file_strm >> value)
list.push_back(value);
file_strm.close();
return 0;
}
else
{
std::cout << "Error" << "\n";
return 1;
}
}
void Read_Data::read()
{
///load data
std::ifstream strm("data.json");
nlohmann::json j = nlohmann::json::parse(strm);
///read ints from data
for (auto const &value : int_list)
int_map[value] = j[value];
///read strings from data
for (auto const &value : string_list)
string_map[value] = j[value];
}