views:

44

answers:

2

I'm working on a program that takes a redirected file as input. For example, if my program was called foo I would call the program with ./foo < input.txt. The files I'm running through my program are supposed to be formatted with a single integer on the first line, two integers on the second line. So something like

3
1 8

I'm finding that some of the files have extraneous characters though on the first line that I need to ignore. Something like

3 t
1 8

I was reading in the data by just doing cin >> var >> var 2 >> var3; but when that extra t gets thrown into the mix it screws everything up. What would be the best way of working around this problem? Is there some way to after I cin the first variable tell it to skip the rest of the line? Or would I use the getline function and then somehow parse that? Thanks.

+1  A: 

If the file is of the form

[number] garbage
[number] [number] garbage

and you know that the numbers are always in the correct position on the line, then I'd use std::getline() to read each line then attempt to read the expected number of integers from each line that you read.

James McNellis
That's kinda what I was thinking. Any recommendation on how to parse each line?
blcArmadillo
@blcArmadillo: Yes; use an `istringstream`, read the two integers, check for errors, and ignore the rest of the contents of the stream.
James McNellis
+1  A: 

Yes, the obvious way would be to use std::getline to read a line of text, use the std::string you get from that to initialize an std::istringstream, read the correct number of items from that line, and repeat as needed.

Jerry Coffin