当输入太长时,如何限制C中的scanf函数打印错误? [英] How to limit scanf function in C to print error when input is too long?
问题描述
我想限制 scanf 函数,所以当我输入例如一个 char* 数组 <String...>
超过 30 个字符时,它不会得到它和我的输出会出错.
I want to limit the scanf function so when I enter for example a char* array <String...>
that has more then 30 characters, it will not get it and my output will be error.
我得到了使用 [^n] 或类似内容的提示,但我不明白该怎么做?我知道我可以使用 scanf("%30s"..)
但我不希望输入有效而只是错误.
I got a hint to use [^n] or something like that but I don't understand how to do it?
I know that I can use scanf("%30s"..)
but I don't want the input to be valid and just the error.
任何帮助都会很棒.
推荐答案
如果你必须使用 scanf
那么我相信你能做的最好的事情就是使用宽度说明符,例如:"%31s"
,正如你已经提到的,然后使用strlen
来检查输入的长度,如果输入的长度超过你的长度,则丢弃该字符串并报告错误限制.
If you must use scanf
then I believe that the best that you can do is use the width specifier with something like: "%31s"
, as you've already mentioned, then use strlen
to check the length of the input, and discard the string and report an error if the input is longer than your limit.
或者可能通过在格式字符串中额外使用 %n
来跳过 strlen
,例如"%31s%n"
.
Or possibly skip the strlen
by additionally using an %n
in your format string, e.g. "%31s%n"
.
使用类似 %[^
]
代替 %s
的格式字符串只是指示函数继续读取直到换行,同时消耗其他空白字符道路.如果您希望允许输入包含空白字符,这将非常有用.
A format string using something like %[^
]
in place of %s
simply instructs the function to continue reading until a newline, consuming other whitespace characters along the way. This is useful if you want to allow the input to include whitespace characters.
查看 scanf 的文档(这里是手册页的副本).
Review the docs for scanf (here's a copy of the man page).
这篇关于当输入太长时,如何限制C中的scanf函数打印错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!