Silverspur
Silverspur

Reputation: 923

How to read from a stream first N digits as an integer?

From a stream and an integer N, I have to get the integer represented by the N first digit-characters of the stream.

Here are some examples:

/*------------------------------------------------*/
/*  N  |   Stream content        | Expected value */
/*-----|-------------------------|----------------*/
/*  2  |  123a52test             |  12 (int)      */
/*  2  |  123552a52test          |  12 (int)      */
/*  2  |  12test                 |  12 (int)      */
/*  2  |  12                     |  12 (int)      */
/*  4  |  123552a52test          |  1235 (int)    */
/*  4  |  122a52test             |  -error-       */

Is there a direct solution to do such a thing, or do I have to do the following?

  1. Build a string from the N characters
  2. Create a stringstream and use it to extract the integer

Upvotes: 0

Views: 488

Answers (2)

LambdaBeta
LambdaBeta

Reputation: 1505

There is no built-in way to do this in C++. However you can 'read' exactly N characters, then turn them into integers.

char number[N];
stream.read(number,N);
return atoi(number); // or stringstream ss; ss << number; ss >> ret; return ret;

Upvotes: 1

user6765872
user6765872

Reputation:

you could use a simple loop like this:

for (int i = 0; i < N; i++) {
    if (isdigit(stream[N])) {
        out*=10;
        out+=stream[N]
    } else {
        err = 1; // error flag;
        break;
    }
}

Upvotes: 0

Related Questions