Reputation: 923
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?
Upvotes: 0
Views: 488
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
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