如果代码以以下开头,用户输入和错误处理会更容易fgets()
.
然后使用sscanf()
, strtol()
等来解析。
printf("\n enter a 64 bit operation \n");
char buf[100];
if (fgets(buf, sizeof buf, stdin) == NULL) Handle_IOErrororEOF();
char a;
char b[17]; // use right size arrays
char c[17];
// use width of 16 and %[]
if (sscanf(buf, " 0x%16[0-9abcdef] %c 0x%16[0-9abcdef]", b, &a, c) != 3) {
Handle_Bad_Input();
}
OTOH,只需使用允许十六进制输入的整数格式说明符"%x"
or "%i"
unsigned long long b,c;
if (sscanf(buf, "%lli %c%lli", &b, &a, &c) != 3) {
Handle_Bad_Input();
}
Why char str [20]; scanf("%s", str);
有麻烦:
"%s"
做了三件事:
1) 扫描但不保存所有前面的(0 个或更多)空白 (' '
, '\t'
, '\n '
, etc.).
2) 扫描并保存所有非空白区域。
3)最后到达一个空白。它停止扫描并将空白放回stdin
.
The "%s"
说明符缺少宽度,例如"%19s"
,所以很容易溢出str
sscanf(str, "0x%s%c0x%s", b, &a, c);
也有麻烦。
输入的第一个数字的末尾和后面的数字之间没有空格'+'
, so "%s"
继续扫描。代码不检查返回值sscanf()
然后使用a
, b
, c
. So a
, b
, c
可能无法正确扫描或初始化 - 导致潜在的未定义行为。