如何使用scanf函数验证输入 [英] How to validate input using scanf
问题描述
我如何可以验证通过使用scanf的用户输入。现在,我有这样的事情,但不起作用。
请注意:我的atoi只是为了验证该scanf函数验证工作原理
。 scanf函数(%[0987654321 .-]的,BUF);I =的atoi(BUF);如果我)
指数= I;
使用 scanf()的
通常是用户输入一个糟糕的主意,因为失败离开文件
指针在未知的位置。这是因为 scanf函数
表示扫描格式,并有更多一点的格式化的不是用户输入。
我会建议使用与fgets()
来获得()弦上一条线,然后按的sscanf实际检查和处理。
这也可以让你检查那些你希望(通过一个循环或定期EX pression)字符,东西在 scanf函数
家庭字符串功能是不是真的适合。
举例来说,使用 scanf()的
与%D
或%F
将停在第一个非数字字符因此不会赶上尾错误,如127hello
,它只是给你127,并用它与非界%S
只是乞讨的一个缓冲区溢出。
如果你真的必须使用 []
格式说明(在 scanf函数
的或的的sscanf
),我不认为它的意思是,然后按取值
。
而且,对于一个强大的输入解决方案使用的建议,请参阅here.一旦你有一个输入线作为字符串,可以的sscanf
你的心内容。
How can I validate the user input by using scanf. Right now I have something like this, but doesn't work.
NOTE: I have the atoi just to validate that the scanf validation works.
scanf("%[0987654321.-]s",buf);
i = atoi(buf);
if(i)
index = i;
Using scanf()
is usually a bad idea for user input since failure leaves the FILE
pointer at an unknown position. That's because scanf
stands for "scan formatted" and there is little more unformatted than user input.
I would suggest using fgets()
to get a line in, followed by sscanf()
on the string to actually check and process it.
This also allows you to check the string for those characters you desire (either via a loop or with a regular expression), something which the scanf
family of functions is not really suited for.
By way of example, using scanf()
with a "%d"
or "%f"
will stop at the first non-number character so won't catch trailing errors like "127hello"
, which will just give you 127. And using it with a non-bounded %s
is just begging for a buffer overflow.
If you really must use the []
format specifier (in scanf
or sscanf
), I don't think it's meant to be followed by s
.
And, for a robust input solution using that advice, see here. Once you have an input line as a string, you can sscanf
to your hearts content.
这篇关于如何使用scanf函数验证输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!