I know that there's many questions here about reading lines from a text file and storing it in a c++ struct. However, those questions all contain text files that have precisely the information they needed, such as a text file with :
Tom 123
Jim 234
However, what if my text file had something like
// The range of 'horizontal' indices, inclusive
// E.g. if the range is 0-4, then the indices are 0, 1, 2, 3, 4
GridX_IdxRange=0-8
// The range of 'vertical' indices, inclusive
// E.g. if the range is 0-3, then the indices are 0, 1, 2, 3
GridY_IdxRange=0-9
How would I be able to get just the numbers 0-8 and 0-9 besides the equal sign in gridX and gridY to be stored in my struct?
What I tried:
struct config {
int gridRange[2];
int gridX;
int gridY;
int cityId;
int cloudCover;
int pressure;
std::string cityName;
};
config openFile(std::string filename, config &con) {
std::fstream inputFile(filename.c_str(), std::fstream::in);
if (inputFile.is_open()) {
std::string line;
for (int i = 0; i < 2; i++) {
while (std::getline(inputFile, line)) {
inputFile >> con.gridRange[i];
std::cout << con.gridRange[i]; //to show what is stored in the array
}
}
//std::cout << range << std::endl;
std::cout << std::endl;
return con;
}
else {
std::cout << "Unable to open file" << std::endl;
}
}
Ignore the other variables in the struct as I still do not need them yet. The output I got was
// The range of 'horizontal' indices, inclusive
0
I managed to solve this by adding in if (line[0] != '/' && !line.empty()) {
inside the while
loop and creating a new string variable called lineArray[5]
. The function now looks like this
config openFile(std::string filename, config &con) {
std::fstream inputFile(filename.c_str(), std::fstream::in);
if (inputFile.is_open()) {
std::string line;
std::string lineArray[5];
int count = 0;
while (std::getline(inputFile, line)) {
if (line[0] != '/' && !line.empty()) {
lineArray[count] = line;
count++;
}
}
std::cout << "Printing out " << lineArray[0] << std::endl;
std::cout << std::endl;
return con;
}
else {
std::cout << "Unable to open file" << std::endl;
}
}
And the output I'll get is Printing out GridX_IdxRange=0-8
.