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

c++ validate input value before add it to array

本文关键字:验证 数组 输入 添加 C++      更新时间:2023-10-16

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

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");