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

时间:2017-03-22 15:12:19

标签: c++ arrays validation

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

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;
}

这怎么可能?

3 个答案:

答案 0 :(得分:2)

您的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和输入类型作为附加参数传递。

答案 1 :(得分:0)

维托里奥上面的回答是现场。为了完整起见,如果您只想要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;
    }
  }
}

答案 2 :(得分:0)

替换

cin >> temp;

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