rho_0,10
kp_0,8
Beta_kp,6
x_min,5
x_max,8
y_min,9
y_max,5
z_min,4
z_max,7
I want to read from this text file line by line and store each Value in the parameter at the same line. for example, for the first line store 10 in rho_0. I have written as below but I don't think it will save the value for the corresponding parameter. I know that I should split each line by delimiter and then convert string to double (float), but I don't know how to implement it for the lines.
Can someone help me?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main ()
{
string line;
ifstream myfile ("mytext.txt");
if (myfile.is_open())
while ( getline( myfile, line ))
{
cout <<line<<endl ;
}
}
getline can be delimited by each comma by adding ',' as a third parameter.
istream >> operator can then we used to extract the number after the comma.
Also, the "myfile >> std::ws" part just consumes any whitespace before calling newline.
Thanks alot for your nice explanation, but I think still your program does not store value in the Parameters.
for examle If I want to cout 'xmin', according to your programm
It will give the error:
'x_min' was not declared in this scope.
Because at the next step I want to use x_min and x_max ... to calculate Volume. I mean
double Volume=(x_max-x_min)*(y_max-y_min)*(z_max-z_min) ; something like this is wrong?
Variable names do not exist at run-time. You can't dynamically have a new variable name based off what's in the file.
Instead, if you use a std::map to store the values (mapping a string to number), like how seeplus did it, you can access or set a specific paramter's value through the std::map.
1 2 3 4 5 6 7
std::map <std::string, double> names;
// ... { add all the names & values from the file to the map through my or seeplus's method }
double& x_max = names["x_max"];
double& x_min = names["x_min"];
double Volume = x_max - x_min; // etc.