C++ reading in specific segments of data from a file redirected to my program
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 extraneo开发者_如何学运维us 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.
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.
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.
精彩评论