如何限制scanf函数的功能在C打印错误,当输入太长? [英] How to limit scanf function in C to print error when input is too long?

查看:241
本文介绍了如何限制scanf函数的功能在C打印错误,当输入太长?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要限制scanf函数的功能,所以当我如输入的char *数组<弦乐...> 有超过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函数(%30秒。),但我不希望输入的是有效的,只是错误。

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.

或可能跳过的strlen 通过在格式字符串,例如还使用%N 31S%%N

Or possibly skip the strlen by additionally using an %n in your format string, e.g. "%31s%n".

使用类似的格式字符串如%[^ \\ n] %S 的简单指示功能继续阅读,直到一个换行符,消费沿途其他空格字符。如果你想允许输入包含空格字符,这非常有用。

A format string using something like %[^\n] 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).

这篇关于如何限制scanf函数的功能在C打印错误,当输入太长?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆