I have a file full of lines in this format:
1 - 2: 3
I want to only load numbers using C++ streams. Whats the most elegant way to do it? I only thought about cin.get() and checikng each char if it is number or not.
I have a file full of lines in this format:
1 - 2: 3
I want to only load numbers using C++ streams. Whats the most elegant way to do it? I only thought about cin.get() and checikng each char if it is number or not.
You can use a locale to change what things are read from the file as it is being read. That is, you will filter out all non-numeric values:
Then when you read your file, it'll convert all non digits to spaces while leaving you only the numbers. After that, you can simply use your normal conversions to transform what is being read into ints.
Response to the comments below:
Here is what I did to get it to work
And this put only the ints into the vector, nothing more, nothing less. The reason it wasn't working before was two fold:
Simply,
Sorry Konrad, but I recommend: never on pain of death, never never never (is that clear enough? :-) read formatted data from a file. Just don't.
There is only one correct way to do input of formatted data: read chunks of characters (typically lines but you can also read fixed length blocks).
Then parse the input text. You're not going to do a cursory check, you going to use a parser that guarantees to catch any formatting error, and report that error in a comprehensible way, take appropriate action (termination, skip the line and continue, whatever).
Separate input (the I/O operation) from parsing.
This advice from decades of experience as a commerical programmer: reading formatted input is for micky mouse proof-of-principal programs. Even if you have exclusive control of the creation of the file, always parse and check and report errors: after all, stuff changes, it may work today but not tomorrow.
I've been writing C++ for decades and I've never read an integer.
I would recommend doing at least cursory sanity checks when reading this:
I think this one would be the fastest -yet elegant- way:
Input:
Output:
See yourself here : http://www.ideone.com/DT9KJ
Note: this can handle extra spaces also. So you can read even this:
Similar topic:
Using ifstream as fscanf