c++ - 必须满足 ceratin 规范的 Scanf-reading 变量

标签 c++ c variable-assignment scanf

我必须解决一个乍一看对我来说非常简单的练习。但是,我不太确定如何解决它。鉴于变量ab 具有某些可接受的值,我是否应该在读取它们后验证它们是否在正确的范围内?而关于变量b,在示例中它是用科学记数法给出的,所以我应该使用e说明符来读取它吗?最后但同样重要的是,',' 的赋值抑制是使用 "%*[,]"?

Write a set of statements to read from the standard input three variables a, b and c, where the variables have the following types:

a – unsigned short integer, b – float, c – string of at most 31 characters

The 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, gscanf()中都是等价的> 家庭。所以使用看起来合适的东西: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对于float9749273.0需要24位来准确表示。由于这种格式对普通数字有 23+1 位精度,所以一切都很好。应注意浮点值的范围测试。

关于c++ - 必须满足 ceratin 规范的 Scanf-reading 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19876569/

相关文章:

c++ - 动态地向一组中的一个对象发射信号

c++ - 无法显示世界中的顶点

android - 从sd卡动态加载共享库

c - Tibco RV C 客户端停止接收消息

python - 在 numpy 数组中赋值

c++ - 在 map 中使用字符串 vector

c++ - 访问冲突读取位置0xfeeeefef2 多线程编程c++ windows

python - 在 Windows 8 上为 python 2.7 构建带有多个 pyx 文件的 cython

c - 尝试使用#define 将字符串数组分配给变量时出错(无效的初始值设定项错误)

c - 我们不能在全局范围内编写任何赋值语句,为什么?