subrata
subrata

Reputation: 151

How to read numrical value from a data file in c++ with comments (like Fortran)

I want to read the value of some parameters from a data file. But the data file contains comments after each line starting with ! (it may be symbols like #, //). How to do this with a program like the following,


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

int main(){
    ifstream inFile;
    inFile.open("input.data");
    int V1;
    double p,q,r,s;
    inFile>>V1>>p>>q>>r>>s;
    return (EXIT_SUCCESS);
}

and the data file is this input.data

5000 0.25   64       !comments here
0.3           !comments here
78.025                !comments here

or


5000 0.25   64                 !comments here
0.3                            !comments here
78.025                         !comments here

Upvotes: 0

Views: 48

Answers (2)

Marek R
Marek R

Reputation: 38092

I prefer slice things to smaller pieces:

using LineData = std::vector<double>;
using Data = std::vector<LineData>;

LineData load_line_data(std::istream& input)
{
    LineData result;

    std::copy(std::istream_iterator<double>{}, {}, std::back_inserter(result));

    return result;
}

Data load_data(std::istream& input)
{
    Data result;
    std::string line;
    while (std::getline(input, line)) {
        std::istring_stream line_stream{ line };
        result.push_back(load_line_data(line_stream));
    }
    return result;
}

Data load_data(const std::string& fileName)
{
    std::ifstream f{fileName};
    return load_data(f);
}

Data format is not explained well so this is a general solution.

With precise specification: what is in each line, this can be done in different way.

Upvotes: 1

Caleth
Caleth

Reputation: 63039

You can discard the rest of the lines after reading the numbers that appear on those lines.

std::string ignored;
inFile >> V1 >> p >> q;
std::getline(inFile, ignored);
inFile >> r;
std::getline(inFile, ignored);
inFile >> s;

Upvotes: 3

Related Questions