Commented data file

M

Moin

In FORTRAN 90/95, one can include comments with each input data line; for eaxmample
19 37 59 ! A set of prime numbers
25 64 81 225 ! A set of perfect squares
Is it possible to include such comments in an input data file for C/C++?
 
K

Kevin McCarty

In FORTRAN 90/95, one can include comments with each input data line; foreaxmample
19 37 59 ! A set of prime numbers
25 64 81 225 ! A set of perfect squares
Is it possible to include such comments in an input data file for C/C++?

Sure. Real quick and inelegantly, here is a program that will read
your example data if it's in a text file. But there's no higher-level
standard library function that will do it "automatically" if that's
what you're asking. Of course you could modify the code below
somewhat and easily write one yourself.


#include <fstream> // ifstream
#include <sstream> // stringstream
#include <iostream> // cout, endl -- for testing
#include <string>
#include <vector>
#include <iterator> // istream_iterator, back_inserter
#include <algorithm> // copy

using namespace std;

int main(int argc, char ** argv)
{
// too lazy to put in error checking, assume this works
ifstream in(argv[1]);
string line;
vector<vector<int> > numbers;

while (getline(in, line)) {
// Strip everything at and after '!' if present
// You could actually even omit this line and the first
// copy() line below would still stop at '!' since it
// can't be interpreted as an integer.
line = line.substr(0, line.find('!'));

// parse line -- again, no error checking
stringstream s(line);
numbers.emplace_back(); // C++2011
copy(istream_iterator<int>(s), istream_iterator<int>(),
back_inserter(numbers.back()));

// make sure it works by printing numbers to console
copy(numbers.back().begin(), numbers.back().end(),
ostream_iterator<int>(cout, " "));
cout << endl;
}

// now numbers[0] == { 19, 37, 59 } and
// numbers[1] == { 25, 64, 81, 225 }

return 0;
}
 
R

Rui Maciel

Moin said:
In FORTRAN 90/95, one can include comments with each input data line; for
eaxmample 19 37 59 ! A set of prime numbers
25 64 81 225 ! A set of perfect squares
Is it possible to include such comments in an input data file for C/C++?

Of course. You just need to define your data format and write a parser that
supports it. Here's a link to a small C++ parser for a INI-inspired data
format.

http://sourceforge.net/projects/minip/


Rui Maciel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,134
Messages
2,570,779
Members
47,336
Latest member
DuaneLawry

Latest Threads

Top