I want to write a c++ code, which will read in a file like this:
A: 10
B: 20
C: 30
while in the code, I would need the value of A B C, how can I let the cin ignore the labels like A:?
of course, I can write a file as
10
20
30
.
.
.
and use cin>>A>>B>>C; to read in those
but in this way, when the number of values increase, it is really hard to remember who is who? Please give some suggestions. I'll appreciate it if you can provide some sample code. Thanks a lot!
There are other methods; for instance, make the stream imbue a locale with a custom ctype where every character other than the decimal digits is a white space character.
None of them would be simpler than just reading the text and discarding it. It can't get any simpler than that, can it?
If the text does not contain an embedded :, except as the last character which is guaranteed to be present, another equally simple way would be to extract and throw away characters up to, and including the last colon.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <sstream>
#include <limits>
int main()
{
std::istringstream stm( "A: 10\n""B: 20\n""C: 30\n" ) ;
constexprchar delimiter = ':' ;
constauto max = std::numeric_limits<std::streamsize>::max() ;
int number ;
while( stm.ignore( max, delimiter ) >> number ) std::cout << number << '\n' ;
}