Search code examples
c++data-structuresfile-iofortrandataformat

C++ equivalent to Fortran Namelist


My question is nearly-identical to C equivalent to Fortran namelist

The key difference is that I'm using C++/17 and wanted to know if there is a more C++ idiomatic manner of solving the issue.


Solution

  • There is no equivalent to Fortran's Namelist in C++. And there is no portable way of achieving this.

    If you want to achieve a similar construct, you'd need some general parsing function working with lines on an istream:

    • It would read lines and ignore anything following a "!";
    • It would read the name that follows the first "&" to see if it matches the expected name;
    • It would stop reading when encountering a sole "/" on a line;
    • It would parse every line in-between, finding the a string with the name of the variable, the "=", and a string with the value on the right of the equal operator, and store the two strings in a std::map<std::string,std::string>.

    For ad hoc reading, you'd call the parsing function to transform istream lines into the map. You would then access the map to initialise the variables. An easy and powerful way would be to use a stringstream sst(my_map["variable name"]); sst>>my_variable;

    If the Namelist would correspond more or less to a class or a struct X, the idiom would then be to overload a friend istream& operator>> (istream&, X&);. This overloaded extractor would then work as in the ad-hoc case to initialise the member variables.

    Of course, I simplify somewhat the algorithm, since you'd also need to cope with errors in the input file: what do you do if an expected variable is missing ? what do you do if the value read is incompatible with the target variable ?

    If you are migrating Fortran code to C++ and you must to use Namelist to avoid disruptions, this could be a portable way to go forward.

    But if it's just an habit of yours, and the file format is not mandatory, then you may consider using json, with one of the many libraries existing to read and write this format (22 libraries are listed on the linked page). The advantage is that you don't have to reinvent the wheel, you'd be more interopearble with a lot of other languages, and json seems more future-proof.