[英]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. 从流和整数
N
,我必须获得由流的N
第一位数字字符表示的整数。
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? 是否有直接的解决方案来做这种事情,还是我必须做以下事情?
There is no built-in way to do this in C++. 在C ++中没有内置的方法可以做到这一点。 However you can 'read' exactly N characters, then turn them into integers.
但是,您可以“读取”正好N个字符,然后将它们转换为整数。
char number[N];
stream.read(number,N);
return atoi(number); // or stringstream ss; ss << number; ss >> ret; return ret;
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.