I'm new to programming in C++ and I'm not sure how exactly the input and output stream work. I want to take a txt file, which contains strings and characters that are separated by a delimiter (': '), to assign class member variables.
So far I been able to have a txt file that contains a single double or integer per line and assigned them to variables. Currently what I have:
Current "Default.txt"
10
3
0.80
1.5
The code that I'm currently using for variable assignment:
#include <iostream>
#include <fstream>
RandomObject::RandomObject(){ //The Default Constructor
std::ifstream my_file;
my_file.open("Default.txt");
//Not sure if this the most effective way to do this...
if (my_file.is_open())
{
while (~my_file.eof())
{ my_file >> Var1; //Var1 is now an int with value 10
my_file >> Var2; //Var2 is now an int with value 3
my_file >> Var3; //Var3 is now double with value 0.80
my_file >> Var4; //Var4 is now double with value 1.5
break;
}
}
my_file.close();
}
Now I want the txt file to be:
The new "Default.txt"
Number Per Dimension: 10
Number of Dimensions: 3
Number Density: 0.80
Initial Temperature: 1.5
I want the value after the colon to be assigned to a member variable:
int Var1 = 10;
int Var2 = 3;
double Var3 = 0.80;
double Var4 = 1.5;
and some output text indicating variable intialization of either:
"Variable 1 is set to 10"
or
"Number Per Dimension is 10".
How do I go about doing this? The txt file will have all the values in the same order, although it might be useful to have program read "Number Per Dimension" as the first string to automatically assign 10 to Var1 if thats possible.
I'm guessing the first step is somehow to split it into two strings with ': ' as the delimiter and store it in some temporary string array variable? I'm not sure what exactly is going on with the reading the line and storing the value in my code above.
I would like to understand how the file stream actually works. Sorry that the formatting is bad.