0

This is my text file (mytext.text):

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 this code:

#include <iostream>
#include <fstream>
#include <string>
    
using namespace std;
    
int main ()
{
    string line;
    ifstream myfile("mytext.txt");
    
    if (myfile.is_open())
        while (getline(myfile, line))
        {
            cout << line << endl;
        }    
    }

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 each line.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Amir
  • 3
  • 1
  • 1
    [Use option 2 of this linked answer as a base](https://stackoverflow.com/a/7868998/4581301). Where it uses `>>` to split up the line, you want another `getline`, specifically something like `getline(iss, token, ',')` to split on the comma. To convert `token` from a `std::string` to a double, [use `std::stod`](https://en.cppreference.com/w/cpp/string/basic_string/stof). – user4581301 Oct 22 '20 at 17:10
  • 1
    You;; probably want to use a map data structure in order to store the values: http://www.cplusplus.com/reference/unordered_map/unordered_map/ You can't dynamically declare new names for variables so you need to store your values in some kind of container. – hbejgel Oct 22 '20 at 17:10

1 Answers1

1

You'll want to use a map data structure of some sort to store parameter values. You'll probably want std::unordered_map for this. Like @user4581301 said, you can use std::getline with a specific delimiter, like a comma.

std::unordered_map<std::string, float> params;
std::ifstream myfile("mytext.txt");
std::string param_name;
float param_value;
while (std::getline(myfile, param_name, ',')) {
    myfile >> param_value;
    myfile.get(); // discard newline
    params.insert({ param_name, param_value });
}

This code doesn't handle invalid input, so you can add error handling if you want.

Anonymous1847
  • 2,568
  • 10
  • 16
  • 1
    I would suggest using `myfile.ignore(numeric_limits::max(), '\n')` instead of `myfile.get()`. Alternatively, don't use `','` on the outer `getline()` at all, and then use `istringstream` to parse each line inside the loop, eg: `while (std::getline(myfile, line)) { istringstream iss(line); getline(iss, param_name, ','); iss >> param_value; params.insert({ param_name, param_value }); }` – Remy Lebeau Oct 22 '20 at 17:54