get variable number of ints

R

Rob

Hi. I want to write code to input N integers from a line of a file.
It should give an error if it encounters a newline before N integers
are read, and also give an error if a newline is not encountered after
the Nth integer. I would imagine the code to look something like

ifstream fin("foo");
int i, k;
for (i = 0; i < N; i++) {
fin.<get> something;
if (something == integer) k = something;
else if (something == newline) error;
}
fin.<get> something;
if (something != newline) error;

but I don't know what function <get> would be, what format to use for
"something", or how to detect a newline.

Any help would be greatly appreciated. Thanks!
 
J

Jerry Coffin

Hi. I want to write code to input N integers from a line of a file.
It should give an error if it encounters a newline before N integers
are read, and also give an error if a newline is not encountered after
the Nth integer. I would imagine the code to look something like

I'd use std::getline to read in a line. Then use a std::stringstream
to read N integers from that line. If you can't convert N integers,
it fails. If there's anything left in the stringstream after you do
read N integers, it fails. Otherwise, it succeeds.
 

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,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top