我必须解决一个乍一看对我来说非常简单的练习。但是,我不太确定如何解决它。鉴于变量a
和b
具有某些可接受的值,我是否应该在读取它们后验证它们是否在正确的范围内?而关于变量b
,在示例中它是用科学记数法给出的,所以我应该使用e
说明符来读取它吗?最后但同样重要的是,',
' 的赋值抑制是使用 "%*[,]"
?
Write a set of statements to read from the standard input three variables
a
,b
andc
, where the variables have the following types:
a
– unsigned short integer,b
– float,c
– string of at most 31 charactersThe input values are separated by one comma. The first variable is given as an octal number. The admissible values for a and b are as follows:
-4331 < a <= 28731 -1035 < b < 9749273
Suitable error messages should be given if the values are not within the allowed range or in the wrong format. Sample input:
12745, -1.e-3, Is this a good one? 0xEE04F, 21e75, Maybe this one... 70073, 21e+6, Or this one. Could this string be too long to put into allocated area?
最佳答案
OP:我读完之后是否应该验证它们是否在正确的范围内?
答:是的。扫描将检查总范围误差。然后代码检查本地范围。
OP:使用 e
说明符读取它?
A: a
, e
, f
, g
在scanf()
中都是等价的> 家庭。所以使用看起来合适的东西:e
是好的。
OP:',' 的赋值抑制使用 "%*[,]"
A:几乎:可以使用“%*1[,]”
,但是“,”
就足够了。
使用 fgets()
和 sscanf()
然后检查范围。
char buf[1000];
if (fgets(buf, sizeof buf, stdin) == NULL) {
handle_EOF_or_IOError();
}
short Number;
float x;
char s[31+1];
if (3 != sscanf(buf, "%ho,%e, %31[^\n]", &Number, &x, s)) {
handle_ParseError();
}
short NumberTooSmall = -4331;
short NumberMax = 28731
float xTooSmall = -1035.0f;
float xTooBig = 9749273.0f;
if ((Number <= NumberTooSmall) || (Number > NumberMax) ||
(x <= xTooSmall) || (x >= xTooBig)) {
handle_RangeError();
}
注意:当解析的字符串开始于“12745, -1.e-3, Is this a good one?”等时有一个微妙的问题。OP 说 ,
是分隔符。这意味着字符串以 "Is this ..."
开头。我认为 OP 想要跳过前导空格并获得 "Is this ..."
。
假设IEEE binary32对于float
,9749273.0
需要24位来准确表示。由于这种格式对普通数字有 23+1 位精度,所以一切都很好。应注意浮点值的范围测试。
关于c++ - 必须满足 ceratin 规范的 Scanf-reading 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19876569/