如何限制c中的输入
我想阻止我的程序接受除 int 之外的任何其他类型的输入。如何检查输入的类型而不将其分配给变量?在C中
I want to prevent my program from any other types of input instead of int. How to check the type of an input without assigning it to a variable? in C
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅 strtod、strtol 和朋友们。
所有这些函数都带有一个输出参数(通常称为
endptr
),该参数显示转换结束的位置。您可以使用该信息来确定要转换的输入是整数、浮点数还是根本不是数字。该策略是尝试将输入解析为以 10 为基数的长度。如果这不起作用(即如果存在未转换的字符),请查看将其解析为双精度是否有效。如果两者都不起作用,则输入不是数字。显然,您必须决定要对数字使用哪种基本类型。您可以进行更多检查和改进,但这里是一个简单的示例。
See strtod, strtol and friends.
All of those function take an out parameter (generally referred to as
endptr
) which shows you where the conversion ended. You can use that information to decide if the input you wanted to convert was an integer or floating point number or not a number at all.The strategy is to try to parse the input as a base 10 long. If that does not work (i.e. if there were unconverted characters), see if parsing it as a double works. If neither works, the input is not a number. Clearly, you would have to decide what basic type you would want to use for numbers. You can build in more checks and refinements, but here is a simple example.
您应该将其放入 char 变量(或字符串)中检查其有效性,然后将其放入 int var 中。
你必须将数据读取到某个地方。
you should put it into a char variable (or a string) check it's validity, and then put it to the int var.
you have to read the data to somewhere.
如果不将输入分配给变量,您就不可能做到这一点。
Without assigning the input to a variable you cannot possibly do this.