C ++输入失败:在单个语句中的多个输入 [英] C++ input failure: multiple inputs in a single statement

查看:232
本文介绍了C ++输入失败:在单个语句中的多个输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的C ++教授坚定地说,在检查输入失败时,必须对每个单独的输入使用单独的 while()循环。他表示以下检查多个输入的方法在单个 cin 语句中收集不起作用:

My C++ professor is adamant that when checking for input failure, one must use separate while() loops for each individual input. He indicated that the following method of checking more than one input gathered in a single cin statement would not work:

while (!good){
    cout << "Enter the length and the width of the rectangle: ";
    cin >> length >> width;
    if(!cin){
        cout << "Bad input, try again" << endl;
        cin.clear();
        cin.ignore(200, '\n');}
    else {
        good = true;}}

他建议的方法:

bool good = false;
while (!good){
    cout << "Enter the length rectangle: ";
    cin >> length;
    if(!cin){
        cout << "Bad input, try again" << endl;
        cin.clear();
        cin.ignore(200, '\n');}
    else {
        good = true;}}  
while (good){
    cout << "Enter the width rectangle: ";
    cin >> width;
    if(!cin){
        cout << "Bad input, try again" << endl;
        cin.clear();
        cin.ignore(200, '\n');}
    else {
        good = false;}}

我的方法似乎工作正常。如果为任一输入输入非数字字符,循环将提示输入新输入并清除故障状态。

My method above seems to work just fine. If non-numerical characters are inputted for either of the inputs, the loop will prompt for new input and clear the fail-state.

它被认为是不好的形式对于输入失败,我做了?我希望能够更清楚地了解我为什么我的方法是错误的。如果我的方法是错误的,有没有办法检查输入失败,而不使用单独的循环为每个单个用户输入?我主要问,因为我编写的程序涉及从一个文件获取许多输入,并单独检查每个变量似乎过于乏味。我认为必须有更好的方法。

Is it simply considered bad form to check for input failure as I have done? I'm hoping to learn more clearly why my method is erroneous. If my method is faulty, is there a way to check for input failure without using separate loops for every single user-input? I mainly ask because I'm writing a program that involves getting many inputs from a file, and individually checking each variable seems overly tedious. I'm thinking there must be a better way.

推荐答案

两者都是正确的,因为他们从失败的输入恢复,用户的另一个机会。

Both are "correct" in that they recover from failed inputs and give the user another chance.

两者都只用于交互式输入。你提到从文件中读取 - 真的没有恢复可能。忽略已损坏的字段只会导致下一个字段被消耗,并且与其在文件中的位置表示不同。从文件读取时的最佳操作方法是尽可能地输出解释(确切地说,在文件中错误发生的位置,例如行和列数,期望什么类型的数据,以及遇到的数据无效) 。

Both are only useful for interactive input. You mention reading from a file -- there's really no recovery possible. Ignoring a mangled field will simply cause the next field to be consumed and interpreted differently from what its location in the file indicates. Best course of action when reading from a file is to output as good an explanation as possible (exactly where in the file the error occurred, e.g. line and columns numbers, what kind of data was expected, and what about the data encountered was invalid).

在交互式使用中,清除缓冲区并再次提示是有用的..您的版本的缺点是,输入正确的长度后,如果用户fat-finger的宽度,他们不能只是重新输入错误的数据,但必须再次键入长度。

In interactive usage, clearing the buffer and prompting again is useful.. Your version has the disadvantage that after entering a length correctly, if the user fat-fingers the width, they can't just re-enter the wrong data, but have to type the length a second time as well.

第二次写循环是不可思议的,然而。相反,你应该编写一个辅助函数,如:

Writing the loop a second time is incredibly pointless, however. Instead you should write a helper function, something like:

template<typename T>
T prompt_for_value( const char* const prompt )
{
    T result;
    while (true) {
         std::cout << prompt << std::flush;
         if (std::cin >> result) return result;
         std::cout << "Bad input, try again" << std::endl;
    }
}

double width = prompt_for_value<double>("Enter the width in meters: ");
double height = prompt_for_value<double>("Enter the height: ");

请注意,代码总体更短,避免了笨重的使用 变量,它反映了其原始代码中途的含义。此外,调用网站现在是非常干净,完全侧重于重要的信息 - 提示和输入的数据类型。

Notice that the code is shorter overall and avoids the clunky use of the good variable which inverted its meaning halfway through the original code. Also, the call site now is very clean and focuses completely on the important information -- the prompt and the data type of the input.

感谢C ++ 11 lambda支持,现在也很容易添加参数验证到帮助函数:

Thanks the C++11 lambda support, it's now also very easy to add parameter validation to the helper function:

T prompt_for_value( const char* const prompt, std::function<bool(T)> validation = {} )
{
    T result;
    while (true) {
         std::cout << prompt << std::flush;
         if (std::cin >> result) {
             if (validation && !validation(result)) {
                 std::cout << "Input out of range, try again" << std::endl;
                 continue;
             }
             return result;
         }
         std::cout << "Bad input, try again" << std::endl;
    }
}

double width = prompt_for_value<double>("Enter the width in meters: ",
                                        [](int w) { return w >= 0; });
double height = prompt_for_value<double>("Enter the height: ",
                     [&width](int h) { return (h >= 0) && (h <= 10000.0 / width); }));

这篇关于C ++输入失败:在单个语句中的多个输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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