Read the numbers in a file while ignore text?

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!
Last edited on
Something like this (example uses a std::istringstream in place of a std::ifstream):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::istringstream stm( "A: 10\n"
                            "B: 20\n"
                            "C: 30\n" ) ;

    std::string text ;
    int number ;
    while( stm >> text >> number ) std::cout << number << '\n' ;
}

http://ideone.com/mvLGUw
Thanks, JLB. This method will work, I believe.
Is there other simpler method? Thanks.
> Is there other simpler method?

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?
Thanks JLB!
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" ) ;

    constexpr char delimiter = ':' ;
    const auto max = std::numeric_limits<std::streamsize>::max() ;

    int number ;
    while( stm.ignore( max, delimiter ) >> number ) std::cout << number << '\n' ;
}

http://ideone.com/hjj7BX
Topic archived. No new replies allowed.