我们如何检查用户输入的任何数据类型值是否正确? [英] how can we check the any data type value entered by the user is correct or not?

查看:104
本文介绍了我们如何检查用户输入的任何数据类型值是否正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何检查用户输入的任何数据类型值是否正确?或者,如果任何用户在该程序中输入整数值,则程序将运行,否则,如果他输入浮点值而不是整数,则将发生异常.如果使用if条件怎么办?如果要进行类型检查,我应该怎么写?

how can we check the any data type value entered by the user is correct or not? or if any user enter in this program the integer value then the program will run otherwise if he enters a floating value in place of integer an exception should occur. How it will be possible with an if condition?What should i write in if condition for type checking ?

void main()
{
   int val;
   try
   {
      cout<<"Enter an value :";
      cin>>val;
      if(  )
      {
          throw 2;
      }
      else
      {
          cout<<"You entered an integer value";
      }
   }
   catch(int x)
   { 
          cout<<"You should eneter an integer value..";
   }
   getch();
}

推荐答案

可能是最好的方法,在这种简单情况下是:
Probably the best way, in such a simple case is:
  1. 接受string作为输入.
  2. 扫描自己的字符串以查找无效字符.


好问题,值得更详尽的解答.

C ++ I/O模型


C ++ I/O背后的想法是,输入和输出表示为两个无限的基本类型序列(通常称为字符",并通过char wcahr_t实现),可以按顺序检索,并且可以转换为所有已构建的通过语言环境类"的方面"提供的一组过程中的-in类型或STL基本类型(字符串),其默认实例隐式地注入"到了tur提供客户端接口的流类中(<< ;和>>运算符).

这些无穷字符序列"(流"的长名称)来自何处或去向何处,语言未指定.

就是说,通用程序"不应假定它们必然绑定到任何最终用途处理的设备:可能的bi文件,网络套接字,或任何可以吐出"或排出"字符的东西. >
由于这些事实,C ++ I/O相对较差:如果输入满足其指定的类型,则将其读取,否则,该流将被阻塞为错误条件,从而以某种方式对重置进行分析.
对于非常琐碎的任务(或对于任务,输入格式进行严格定义),这足以满足需要,对于较复杂的任务(对于其中输入可能是错误的或不可预测的或无法按固定顺序组织的机器人)来说,C ++ I/O模型几乎可以不支持.

用户模型


基本上有三种类型的应用程序(加上更多派生类):
Good question, that deserves a more elaborated answer.

The C++ I/O model


The idea behind the C++ I/O is that Input and Output are represented as two infinite sequence of elementary type (generically called "character", and implemented though char or wcahr_t) retrievable in sequence and possibly convertible into all the built-in type or STL basic types (strings) across a set of procedure provided through "facets" of a "locale class" whose default instance is implicitly "imbued" into the stream classes that in tur provide the client interface (the << and >> operators).

Where does those "infinite sequence of characters" (long name for "stream") comes from or go to is left unspecified by the language.

That said, a "general purpose program" should not assume they are necessarily binded to whatever end-use handled device: the could bi files, network sockets, whatever thing that can "spits out" or "drain off" characters.

Because of these facts, C++ I/O is relatively poor: if an input satisfy the type it is designated, is read, otherwise the stream is blocked into an error condition to be somehow analised a reset.
For very trivial task (or for task the input format is rigidly defined) this can be enough, bot for more complex tasks (where input can be somehow erroneous or non predictable or not organized in a rigid sequence) C++ I/O model has almost no support.

The user model


There are essentially three types of applications (plus some more derivative):

  1. 计算机驱动程序
  2. 用户驱动程序
  3. 事件驱动程序


计算机驱动


是计算机在其中逐步告诉用户所需数据的程序.可以通过将C ++流映射到用户控制台来进行仿真,假设终端是输出的显示,键盘是字符生成器.这是cin cout 的操作.
要求用户严格遵守计算机的要求.
健壮的程序检查错误情况,重置流,清理缓冲区并要求重新输入所需的数据.

请注意,这已经违反了标准C ++模型:在C ++模型中,输入和输出是不相关的.输入不是对输出的反应"(不是C ++ I/O知道的东西).
想象一下从文件中读取10个数字.如果其中之一不可读为数字,则应归因于清理缓冲区并再次询问"的原因是什么? 重置并跳过char到下一行定界符然后重试"是一种很好的错误恢复方法吗?还是您只是误读了值? C ++最通用的程序不一定设计为由用户管理.

用户驱动程序


用户界面"程序必须比标准输入先进一步,并且要具有更多的语义".不仅是转换器"(通常是从文本到数字,再到数字是文本),而是由用户可以执行的操作定义的语言"的真正解释器",以及从不一致的操作中恢复的功能.
这是当 >>运算符因支持getline而被解雇,并且文本未从cin转换而来的情况下进行检索(因此使所有iostream类无用的开销)并在最终正确转换之前进行了分析(可能通过与字符串:sstream).
这是典型的情况(请参见
在这种情况下,标准输入可能不像它看起来的那样好:缓冲机制阻止流直到到达行尾"为止,否则可能没有足够的反应性.

事件驱动程序


这是C ++标准输入模型失去吸引力的地方:程序的主循环必须对每个单个键入的字符做出反应(甚至可能对其他用户操作的外围设备(例如鼠标,触摸屏或多点触摸屏)做出响应)标准输入模型,甚至输出模型也变得不够用(可能不再是简单的序列").
不好的是,C ++没有可使用的标准化模型",因此您必须使用基础平台API或使用可用的多平台框架之一.另一个引人注目的方面是,几乎所有它们都基于10年前或10年前的C ++,看起来比现代C ++"的带有类的C"要多得多.
这是必须以某种方式填补的空白.

回到OP问题


您实际上正在运行计算机驱动程序",但是您还希望针对常见错误具有鲁棒性".

我可以提供一些建议:

istream可以用作布尔值,如果不处于良好"状态则为"false"(本质上:如果在上次读取期间出了点问题)
所以:


Computer driven


Are programs where the computer tells the user step by step what data it wants. It can be emulated by mapping C++ streams to a user console, assuming the terminal as a display for output and a keyboard as a character generator. This is what cin and cout do.
The user is required to strictly conform to the computer expectation.
Robust program checks for error condition, reset the stream, cleanup the buffer and ask to re-enter the required data.

Note that this is already a violation of the standard C++ model: in the C++ model input and output are unrelated. The input is not a "reaction to an output" (not something C++ I/O is aware of).
Imagine to read 10 number from a file. If one of them isn''t readable as a number, what dues it mean "cleanup the buffer and ask again"? is "reset and skip the char up to the next line delimiter and retry" a good error recovery? Or are you just misreading the values? A C++ most general program is not necessarily designed to be managed by a user.

User driven programs


A "user interfaced" program must go one step ahead the standard input, and be somehow more "semantic". Not just a "converter" (typically from text to number and number to text) but a real "interpreter" of a "language" that is defined by the action a user can do, and a recover from incongruent actions.
Here is when the >> operator is dismissed in favor of getline, and the text is retrieved unconverted from cin (thus making all the iostream class useless overhead) and analyzed before being finally converted properly (may be through another stream binded to the string: sstream).
And this is the typical situation (see here[^])
The program flow is broken in a set of functionalities the user activates by supplying commands. It typically happens trough textual strings the user is supposed to type. The program itself is a (sort of ) loop that resamble a command interpreter: A string is read, analyzed, "interpreted" and if a command is recognized the corresponding function is called. The loop continue until a "quit" command is given.

In this context, the standard input can be not as good as it may seem: a buffering mechanism that block the flow until a "end of line" if reached may be not enough reactive.

event driven program


Here is where the C++ standard input model loose all its attractive: program whose main loop has to react to every single typed character (an may be even to other user manipulated peripheral, like a mouse or a touch or multitouch surface) cannot fit the C++ standard input model, and even the output model becomes to be inadequate (may be it cannot be anymore a simple "sequence").
What is bad, here, is that C++ has ... no "standardized model" to work with, and hence you have to go down to the underlying platform API, or use one of the multi-platform frameworks available. The other dramatic aspect is that almost all of them are based on what C++ was 10 or more years ago, looking much more "C with classes" that "modern C++".
An this is a gap that has to be somehow filled.

coming back to OP question


You are actually running a "computer driven program", but you also want "robustness" against common error.

Some suggestions I can give:

istream can be used as a boolean value that is "false" if not in "good" state (essentially: if something went wrong during the last read)
so:

cin>>val;
if(!cin) { /*handle error condition */}


可能是识别输入不一致的好方法.
但是,此时的流处于不良"状态.
这需要调用cin.clear(),然后全部读取并忽略垃圾"


Can be a good way to identify input incongruence.
But the stream, at that point, is in "bad" state.
This requires a call to cin.clear() and then read all and ignore the "rubbish"

while(true)
{
   cout<<"Enter an value :";
   cin >> val;
   if(!cin)
   {
      cin.clear();
      cin.ignore(numeric_limits<streamsize>::max(), ''\n'');
      cout<<"Bad input. ";
   }
   else
      break;
}
cout<< "You entered "<<val <<endl;


在这里程序循环直到满足输入为止.
这仍然可以通过与C ++标准输入模型保持一致来完成.

还要注意,我在这里没有使用异常.除非您遇到异常,否则请不要那样使用它们:用户可以错误键入值的事实只是例外",而且-通常-在抛出异常的相同上下文中捕获异常是没有意义的.您可以只使用常规程序结构.
例外的想法是在您的上下文中发生错误,而您无法采取任何措施来纠正/阻止它.这样一来,您就会以为所谓的捕获"可能会回到堆栈中的某个级别,在那里您可以了解有关(失败的)操作目的的更多信息.


Here the program loops until the input is satisfied.
This is the most it can be done by still being aligned to the C++ standard input model.

Note also that I didn''t use exceptions here. Unless if you are experiencing with exception, don''t use them that way: the fact a user can mistype a value is all but "exceptional", and -in general- catching an exception in the same context it has been thrown is pointless. You can just use normal program structures.
The idea of exception is that something wrong happens in your context without you can do anything to correct/prevent it. So that you throw with the idea that what called you will "catch", may be some level back in the stack, where more information are known about the purpose of the (failed) action that where required.


我使用一种称为validate(string myTempString){}的方法,但这是我传输字符串的时间.
在您的情况下,如果您输入其他内容(如double),则会引发异常.
所以你可以做
I use a method called validate(string myTempString){} but this is when i transmite a string.
in your case if you enter something else(like a double) it would trow a exception.
so you can do
try
{
cin>>val;
}
catch()
{
trow 2;
}


这篇关于我们如何检查用户输入的任何数据类型值是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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