c++parsinginputistream

Parsing only numbers from istream in C++


I have a bunch of input files that look like the following:

(8,7,15)
(0,0,1) (0,3,2) (0,6,3)
(1,0,4) (1,1,5)

I need to write a function that parses these inputs one number at a time, so I need to be able to separate the input by numbers, e.g.: 8, then 7, then 15, then 0, another 0, so on.

The only way I've thought of so far is to use istream.get() which returns the next character's ASCII code, which I can convert back to its character format by casting it to char. Then I'd check if the character was a number or not (so the brackets are ignored) but this way, any double (or triple) digit numbers are only read one digit at a time.

What would be the best way to achieve this?

By the way, I must use istream. It's part of the specification that I'm not allowed to change

Thanks


Solution

  • Here's some code, you can adapt to meet your precise needs

    for (;;)
    {
      int ch = in.get();
      if (ch == EOF)
        break;
      if (isdigit(ch))
      {
        int val = ch - '0';
        for (;;)
        {
          ch = in.get();
          if (!isdigit(ch))
            break;
          val *= 10;
          val += ch - '0';
        }
        // do something with val
      }
    }
    

    This is untested code.