gpt4 book ai didi

C++ 输入验证

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:09:55 26 4
gpt4 key购买 nike

我正在开始 C++ 编程,必须进行大量输入验证。我发现这个功能似乎普遍适用,但有一个方面有问题;如果我输入 -90,程序不会报错。我的问题是:1、如何添加input不能<=0的情况?2.有没有更好的方法来限制用户输入?也许是 C++ 中的库?

感谢您的帮助或建议。

#include <ios>  // Provides ios_base::failure
#include <iostream> // Provides cin

template <typename T>
T getValidatedInput()
{
// Get input of type T
T result;
cin >> result;

// Check if the failbit has been set, meaning the beginning of the input
// was not type T. Also make sure the result is the only thing in the input
// stream, otherwise things like 2b would be a valid int.
if (cin.fail() || cin.get() != '\n')
{
// Set the error state flag back to goodbit. If you need to get the input
// again (e.g. this is in a while loop), this is essential. Otherwise, the
// failbit will stay set.
cin.clear();

// Clear the input stream using and empty while loop.
while (cin.get() != '\n')
;

// Throw an exception. Allows the caller to handle it any way you see fit
// (exit, ask for input again, etc.)
throw ios_base::failure("Invalid input.");
}

return result;
}

用法

inputtest.cpp

#include <cstdlib> // Provides EXIT_SUCCESS
#include <iostream> // Provides cout, cerr, endl

#include "input.h" // Provides getValidatedInput<T>()

int main()
{
using namespace std;

int input;

while (true)
{
cout << "Enter an integer: ";

try
{
input = getValidatedInput<int>();
}
catch (exception e)
{
cerr << e.what() << endl;
continue;
}

break;
}

cout << "You entered: " << input << endl;

return EXIT_SUCCESS;
}

最佳答案

你可以使用函数来验证

template <typename T>
T getValidatedInput(function <bool(T)> validator) {
T tmp;
cin >> tmp;
if (!validator(tmp)) {
throw ios_base::failure("Invalid input.");
}
return tmp;
}

用法

int input = getValidatedInput<int>([] (int arg) -> bool {
return arg >= 0;
});

关于C++ 输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25666047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com