繁体   English   中英

C ++在将输入值添加到数组之前验证输入值

[英]c++ validate input value before add it to array

我的目标是在将输入值添加到数组之前先对其进行验证。 当前使用的代码:

int main()
{
    int temp;
    int arr[5];
    for(int i = 0; i < 5; i++)
    {
        // validate here
        cin >> arr[i];
    }
    return 0;
}

和我的验证方法:

int validateInput(string prompt)
{
    int val;
    while (true)
    {
        cin.clear();
        cin.sync();
        cout << prompt;
        cin >> val;
        if (cin.good() && val >= -50 && val <= 50)
        {
            break;
        }
        else
            cin.clear();
        cout << "Invalid input! number must be between -50 and 50" << endl;
    }
    return val;
}

那怎么可能?

您的validateInput应该只处理验证:它应该回答x有效还是无效?”

bool validateInput(int x)
{
    return val >= -50 && val <= 50;
}

stdin读取时,请使用validateInput并相应地分支:

for(int i = 0; i < 5; i++)
{
    int temp;
    cin >> temp;

    if(cin.good() && validateInput(temp))
    {
        arr[i] = temp;
    }
    else
    {
        cout << "Invalid input! number must be between -50 and 50" << endl;
        // handle invalid input
    }
}

如果您想进一步抽象“仅从std::cin读取有效数字”的思想,则可以使用更高阶的函数

template <typename TFValid, typename TFInvalid, typename TFInvalidIO>
decltype(auto) processInput(TFValid&& f_valid, TFInvalid&& f_invalid, TFInvalidIO&& f_invalid_io)
{
     int temp;
     cin >> temp;

     if(!cin.good()) 
     {
         // Invalid IO.
         return std::forward<TFInvalidIO>(f_invalid_io)();
     }

     if(validateInput(temp))
     {
         // Valid IO and datum.
         return std::forward<TFValid>(f_valid)(temp);
     }

     // Valid IO, but invalid datum.
     return std::forward<TFInvalid>(f_invalid)(temp);
}

用法:

for(int i = 0; i < 5; i++)
{
    processInput([&](int x){ arr[i] = x; },
                 [](int x){ cout << x << " is invalid"; },
                 []{ cout << "Error reading from cin"; });
}

如果需要更多通用性,还可以传递validateInput和输入类型作为附加参数。

维托里奥在上面的答案是正确的。 为了完整起见,如果您只需要5个元素:

#include <string>
#include <iostream>

using namespace std;

bool validateInput(int inValue)
{
  return inValue >= -50 && inValue <= 50;
}

int main()
{
  int _arr[5];
  int _currentIdx = 0;
  int _tmp;
  while (_currentIdx < 5)
  {
    cin >> _tmp;
    if (validateInput(_tmp))
    {
      _arr[_currentIdx] = _tmp;
      _currentIdx++;
    }
    else
    {
      cout << "Invalid input! number must be between -50 and 50" << endl;
    }
  }
}

更换

cin >> temp;

arr[i] = validateInput("some str");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM