如何检查用户的输入是否有效?(C++) [英] How To Check If User's Input Is Valid? (C++)

查看:50
本文介绍了如何检查用户的输入是否有效?(C++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在根据一组指令创建程序时,我在设计伪代码和实现实际代码方面做得很好.我觉得我缺少的是检查用户的输入(无论是有效还是无效).当我练习编程时,我创建了自己的方法来检查验证用户的输入.但是代码很长,我觉得不够(我会解释原因).我想知道是否有更好的方法来检查用户的输入.以及其他程序员如何实现他们的代码.

When it comes to creating a program based on a set of instructions, I do pretty well in designing the pseudo-code, implementing the actual code. What I feel like I lack is checking for users' input (whether it's valid or invalid). As I practiced programming, I created my own way for checking for validating users' input. But the code is lengthy and I feel like it's insufficient (I'll explain why). I wanted to know if there is a better way to check for users' input. And how do other programmers implement their code.

这是我验证用户输入的方式:

This is how I validate users' input:

if(cin.fail()) {
        cout << "Invalid Input" << endl;
        cout << "Now Exiting..." << endl;
        return;
}
// I didn't know how to skip a line while in code
while(input < 0) {
        cout << "Invalid Input" << endl;
        cout << "Enter radius: " << endl;
        cin >> input;
        if(cin.fail()) {
             cout << "Error: Invalid Input" << endl;
             cout << "Now Exiting..." << endl;
             return;
        }
}

我之所以在cin未能将值单独存储到变量中时退出的原因(第1-5行,第11-15行)是因为如果我将cin.fail()添加到while条件中并尝试输入一个字母,它开始无限循环.我做了一些研究,我看到你必须先 cin.sync(),然后是 cin.clear().但我仍然得到无限循环.

The reason why I exit out when cin fails to store the value into the variable separately (line 1 - 5, line 11 -15) is because if I add the cin.fail() to the while condition and attempt to input a letter, it begins a infinite loop. I did a little research and I saw you have to cin.sync(), then cin.clear(). But I still get the infinite loop.

代码如下:

do {
        cin.sync()
        cin.clear();
        cout << "Enter radius: ";
        cin >> input;
} while(input < 0 || cin.fail());

如果我做错了什么,看到更好的方法来验证用户的输入会很有帮助.

If I'm doing something wrong, it would very helpful to see better ways to validate user's input.

推荐答案

输入验证的问题是一种简单的解析形式.

The problem of input validation is an easy form of parsing.

有一些语言类(在形式语言理论领域)可以表达您输入的复杂性.这些类被称为常规的、上下文无关的和图灵完备的.

There are language-classes (in the field of formal language theory) that express the complexity of your input. Those classes are called regular, context-free, and turing-complete.

您必须考虑您的程序可能收到的所有可能的输入,并决定您的程序是否应该接受它们.语言类可帮助您确定所需的输入验证类型.

You have to consider all your possible inputs, that your program might receive and decide whether your program should accept them or not. The language classes help you to decide what kind of input validation you need.

如果语言是常规语言(就您而言),您可以使用正则表达式来验证输入.

if the language is regular (as it is in your case) you can use regular expressions to validate the input.

例如,上下文无关语言是数学公式.您无法使用正则表达式计算括号的数量.因此,不可能用正则表达式检查 ((a+b) * (c+d)) 是否有正确数量的括号.

A context-free language for example would be a math-formula. You cannot count the number of parentheses with a regular expression. Therefore it is impossible to check ((a+b) * (c+d)) has the right amount of parentheses with a regular expression.

到目前为止,这些都是关于您应该做什么的提示,当您更自然地编程时.

Up to now these are hints on what you should be doing, when programming comes more naturally to you.

为了简单起见,做一个非常受限的正则表达式,比如手动解析.你真正想用伪代码做什么:

For the sake of simplicity well do a very constrained regular expression like parsing by hand. what you actually want to do in pseudo code:

do {
   std::cout << "Please enter radius: ";

   line = read_a_line_from(std::cin) // separated by '\n' the newline

   if (false == really_read_a_line(line)) {
      /* error handling for std::cin, dealing with i.e.: the fail bit */
      break; /* exit the loop */
   }
   if (line == "exit") { // give the user an explicit exit, to quit gracefully
      exit(SUCCESS); /* exit the program */
   }

   if (false == is_a_number(line)) {
      /* we read something that isn't a number */
      /* we should tell the user he should do as we asked */
      continue; /* jump back to the beginning of the loop */
   }

   unsigned num = convert_number(line);
   unsigned area = calculate_area(num); /* do something with your input */
} while (true);
exit(FAILURE);

这里的代码不是特意让你看到你可以在某些地方做什么,但仍然忽略了实际的实现(用于你的练习).请注意,检查一行是否实际上是数字的一种简单方法是转换.然而,并不是所有要解析的东西都应该同时检查有效性和处理.

The code here is not too specific on purpose that you see what you could be doing in places, still leaving out the actual implementation (for your exercise). Please note that a simple way of checking whether a line is actually a number is by converting. However not all things to parse should be checked for validity and processed at the same time.

另见(尤其是示例):

http://en.cppreference.com/w/cpp/string/basic_string/getline

http://en.cppreference.com/w/cpp/string/basic_string/stol

如何检查是否给定c++ string 或 char* 只包含数字?

这篇关于如何检查用户的输入是否有效?(C++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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