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");
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何在C++中检查2D数组中负值的输入验证
- 在C++中使用字符数组进行输入验证
- C++中的字符数组验证
- 在C++中使用字符数组进行用户输入验证
- C++ 中字符数组的输入验证
- C++中输入字符数组的特定验证
- 队列验证层错误:队列族索引在 pCreateInfo->pQueueCreateInfos 数组中不是唯一的
- 如何使用数组字符串进行输入验证
- C++ 在将输入值添加到数组之前对其进行验证
- 在数组中输入5个元素,检查验证,然后输出C++
- 使用基于C++11范围的循环验证数组值?[无矢量]
- 验证内存设置为默认值后数组中的更改
- C++ 字符数组大小验证
- 在 C 中验证数组的大小
- 数组边界检查和输入验证
- 验证数组没有重复的值