Iago Lemos
Iago Lemos

Reputation: 85

Getting variables values from a .txt file in C++

I am writing a CFD solver in C++ but I am in the very beginning. Now I am coding a solver for the linear convection. The math is ok, working well, but I need to write also a code for reading variables from a .txt file. My code is:

//Code for solving the convection linear equation from Navier-Stokes

#include <iostream>

using namespace std;

int main()
{
    float endtime=0.3; //simulation time
    float dx=0.025;  //element size
    float xmax=2;  //domain size
    float c=1;  //wave velocity
    float C=0.3;  //Courant-Friedrich-Lewy number
    float dt=C*dx/c;  //defining timestep by the Courant equantion
    int nx=xmax/dx + 1;  //defining number of elements
    int nt=endtime/dt;  //defining number of time points

    float u[nx] = { }; //defining an initial velocity array.
    float un[nx] = { };

    for(int i = 4; i <= 9; i++) //defining contour conditions
    {
        u[i] = 2;
    }
    for(int n=1; n<=nt; n++)
    {
        std::copy(u, u + nx, un);
        for(int i=1; i<=nx; i++)
        {
            u[i] = un[i] - c*(dt/dx)*(un[i]-un[i-1]);

        }
    }
    for (int i = 0; i <= nx; i++) 
    {
       cout << u[i] << endl;
    }

    return 0;
}

I need to take these variables values from a .txt, like the end time, element size, etc. Then, I have a .txt called "parameters", which is exactly written like that:

endtime=0.3
dx=0.025
xmax=2
c=1
C=0.3

What's the most effiecient way to get these variables values from this .txt and use it in the code?

Upvotes: 0

Views: 188

Answers (1)

Chad
Chad

Reputation: 19032

Using only standard features:

#include <iostream>
#include <tuple>
using namespace std;

tuple<bool, string, string> read_one_value(istream& in)
{
    string name;

    if(getline(in, name, '='))
    {
        string value;

        if(getline(in, value))
        {
            return make_tuple(true, name, value);
        }
    }

    return make_tuple(false, "", "");

}


int main()
{
    for(auto val = read_one_value(cin); get<0>(val); val = read_one_value(cin))
    {   
        std::cout << get<1>(val) << " -> " << get<2>(val) << '\n';
    }

    return 0;
}

This leaves converting from the value string objects to the needed type as an exercise for the reader, and assumes your format of name=value is consistent.

Upvotes: 4

Related Questions