On 16 mai, 16:54, Victor Bazarov <v.Abaza...@comAcast.netwrote:
C++ Newbie wrote:
Suppose I have a text file with the input:
1 2 3 4 5 6 7 8 9 10 ! Comment: Integers 1 - 10
How do I write a C++ program that reads in this line into a
10-element vector and ignores the comment?
How do you know there are 10 elements?
Or more to the point, does he know? And what determines what is
a comment, and what isn't?
Basically, you read integers and stuff them into a vector
until you get an error or the end of the line. If you get an
error, ignore the rest of the line.
Maybe. Until we know what the actual specification is, any
suggestions are just guesswork. If the specification says that
the '!' character starts a comment, then the simplest solution
might be to use a filtering streambuf, so that characters from
the '!' to the line end simply don't show up in the input.
Although if the syntax is otherwise line oriented, this might be
overkill, since you can use getline, as you propose later. If,
on the other hand, the syntax is 10 elements, and anything else
is a comment, you need some other approach.
I strongly suggest two step processing: first, read a line
from your file, then, second, process the line you just read
to extract the individual integers (until the end of the line
or an error which should mean the end of the vector).
That's generally a good solution if the syntax is line oriented.
If the syntax says that anything following a '!' is a comment,
then it is trivial to trim anything after the first '!' from the
input line. It can be made to work in more complicated cases as
well.
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34