问题描述
首先,关于的sscanf
,因为常见的答案是不使用不回答我的问题,使用相关的其他问题的sscanf
所有并使用与fgets
或残培
来代替,这在我的情况下是不可能的。
First of all, other questions about usage of sscanf
do not answer my question because the common answer is to not use sscanf
at all and use fgets
or getch
instead, which is impossible in my case.
问题是我的C教授希望我在程序中使用 scanf函数
。这是一个必要条件。
然而该方案还必须处理所有不正确的输入。
The problem is my C professor wants me to use scanf
in a program. It's a requirement.However the program also must handle all the incorrect input.
该程序必须读取整型数组。不要紧在什么格式整数
为阵列被提供。为了使工作更容易,程序可能首先读取阵列的大小,然后将每个在一个新行。整数
The program must read an array of integers. It doesn't matter in what format the integersfor the array are supplied. To make the task easier, the program might first read the size of the array and then the integers each in a new line.
该程序必须处理这样的输入(并适当报告错误):
The program must handle the inputs like these (and report errors appropriately):
- 999999999999999 ...(比整数更大的数字)9
- 12A3(不读这是一个整数12)
- A ... Z(串)
- 11 AA 22 33 \\ n的所有在同一行(这可能是由11后丢弃一切处理)
- 输入大于输入数组较大
有可能更不正确的情况下,这些都是只有少数我能想到的。
There might be more incorrect cases, these are the only few I could think of.
如果错误输入提供,程序必须再次要求用户输入,直到
正确的输入给出,但previous正确的输入必须保持(仅适用于不正确
输入必须从输入流清零)。
If the erroneous input is supplied, the program must ask the user to input again untilthe correct input is given, but the previous correct input must be kept (only incorrectinput must be cleared from the input stream).
一切都必须符合C99标准。
Everything must conform to C99 standard.
推荐答案
的 scanf函数
家庭功能无法安全地处理整数尤其是当使用。你提到的第一种情况是特别麻烦。该标准这样说:
The scanf
family of function cannot be used safely, especially when dealing with integers. The first case you mentioned is particularly troublesome. The standard says this:
如果这个对象没有合适的类型,或者如果的结果
转换不能重新在对象 psented $ P $,行为
理解过程网络斯内德。
简单明了。你可能会认为%5D
技巧等,但你会发现他们是不可靠的。或者,也许有人会认为errno的。在 scanf函数
函数的不需要设置错误号
Plain and simple. You might think of %5d
tricks and such but you'll find they're not reliable. Or maybe someone will think of errno. The scanf
functions aren't required to set errno
.
按照此<一个href=\"https://www.securecoding.cert.org/confluence/display/sec$c$c/INT05-C.+Do+not+use+input+functions+to+convert+character+data+if+they+cannot+handle+all+possible+inputs\">fun小页面:他们最终抛弃 scanf函数
完全
Follow this fun little page: they end up ditching scanf
altogether.
所以,回到你的C教授,问他这?的究竟怎样完成任务C99的sscanf这将报告错误的
So go back to your C professor and ask him this: how exactly does C99 mandate that sscanf will report errors ?
这篇关于如何正确,安全地使用的sscanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!