在 C 中,如何限制此 scanf 将采用的可接受值? [英] In C, How can I restrict the accepted values that this scanf will take?

查看:46
本文介绍了在 C 中,如何限制此 scanf 将采用的可接受值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想限制以下 patient_id 变量可以具有的可能值(出于安全原因).以下是我目前拥有的代码,但我很确定这是错误的方法:

I'd like to restrict the possible values that the following patient_id variable can have(for security reasons). The following is the code I currently have, but I'm pretty sure this is the wrong approach:

   void addPatient(){
           int patient_id;
           printf("Enter ID between 10000 & 99999: ");           
           do{
           scanf("%d", &patient_id);
           }while((patient_id<10000)&&(patient_id>99999));

    }

推荐答案

除非您正在为家庭作业问题编写程序,特别是如果您正在编写一个实际的人类用户将以任何严肃的方式与之交互的程序, 不要使用 scanf().一次对输入行进行操作.如果您仍想使用 scanf() 的解析",则可以在拥有完整输入行后使用 sscanf() 等.如果你不知道如何获取用户输入而不是通过 scanf(),一个简单的方法是将 fgets() 放入缓冲区,挑出行,并为下一个 fgets() 准备缓冲区.

Unless you're writing a program for homework problem, and in particular if you're writing a program that an actual human user will interact with in any serious way, don't use scanf(). Operate on lines of input at a time. If you still want to use scanf()'s 'parsing', you can use sscanf() and like on a complete line of input after you have it. If you don't know how to get user input other than through scanf(), a simple way is to fgets() into a buffer, pick out the line, and prepare the buffer for the next fgets().

如果你坚持使用scanf(),我有一个挑战给你:用它来接受同一行的两个ID,用空格隔开.如果用户只输入一个 ID 然后按回车键,您的程序应该在请求更多输入之前向用户抱怨这一点.

If you insist on using scanf(), I have a challenge for you: use it to accept two IDs on the same line, separated by a space. If the user enters only one ID and then hits enter, your program should complain about this to the user before requesting any more input.

这篇关于在 C 中,如何限制此 scanf 将采用的可接受值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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