skipping line while reading data file

I

Ivan Liu

I would like know how I can skip a line while reading
a set of input data (from a text file) if the first character
of the line is "#".

My original code reads:

ifstream Infile("data.dat");

for( int i=0; i<N; i++){
Infile >> x >> y;
}
 
J

Jerry Coffin

I would like know how I can skip a line while reading
a set of input data (from a text file) if the first character
of the line is "#".

My original code reads:

ifstream Infile("data.dat");

for( int i=0; i<N; i++){
Infile >> x >> y;
}


One obvious possibility would be something like this:

std::istream &my_getline(std::istream &is, std::string &s) {
while (std::getline(is, s) && s[0] == '#')
;
return is;
}

for (int i=0; i<N; i++) {
std::string line;
if (!my_getline(Infile, line))
break;
std::stringstream temp(line);
temp >> x >> y;
}

That does raise one minor question: you're starting with a count (N) of
lines to read. Is that count supposed to include the commented lines or
not? The code above attempts to read N lines of actual data -- if you
want a total of N lines, whether they contain data or not, you'd have to
rewrite it a bit.
 
I

Ivan Liu

Thanks. I have a further question..


Jerry said:
One obvious possibility would be something like this:

std::istream &my_getline(std::istream &is, std::string &s) {
while (std::getline(is, s) && s[0] == '#')
;
return is;
}

for (int i=0; i<N; i++) {
std::string line;
if (!my_getline(Infile, line))
break;

Is the if-statement for checking if the Infile does exit?


std::stringstream temp(line);
temp >> x >> y;
}
 
J

Jerry Coffin

[ ... ]
Is the if-statement for checking if the Infile does exit?

It's mostly to check whether we've reached the end of the file (for
example, if the file got corrupted and only contained one line).
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top