stringstream无符号输入验证

Ale*_*eev 5 c++ validation c++11

我正在编写程序的一部分,它解析并验证程序控制台参数中的一些用户输入.我选择使用stringstream用于此目的,但遇到无符号类型读取的问题.

下一个模板用于从给定字符串中读取请求的类型:

#include <iostream>
#include <sstream>
#include <string>

using std::string;
using std::stringstream;
using std::cout;
using std::endl;

template<typename ValueType>
ValueType read_value(string s)
{   
    stringstream ss(s);
    ValueType res;
    ss >> res;
    if (ss.fail() or not ss.eof())
        throw string("Bad argument: ") + s;
    return res;
}
// +template specializations for strings, etc. 

int main(void)
{   
    cout << read_value<unsigned int>("-10") << endl;
}   
Run Code Online (Sandbox Code Playgroud)

如果类型是无符号的,输入字符串包含负数,我希望看到异常抛出(由引起ss.fail() = true).但是stringstream会生成转换为无符号类型的值(书面示例中为4294967286).

如何修复此样本以实现所需的行为(最好不回退到c函数)?我知道它可以通过简单的第一个符号检查完成,但我可以放置前导空格.我可以编写自己的解析器,但不相信问题是如此不可预测,标准库无法解决它.

对于无符号类型,隐藏在stringstream运算符深处的函数是strtoull和strtoul.它们以描述的方式工作,但提到的功能是低级的.为什么stringstream不提供一些验证级别?(我只是希望我错了,但确实需要一些动作来实现这一点).

dyp*_*dyp 2

num_get支持显式检查签名的方面。'-'对于无符号类型,拒绝任何以 a 开头(空格之后)的非零数字,并使用默认的 C 语言环境num_get进行实际转换。

#include <locale>
#include <istream>
#include <ios>
#include <algorithm>

template <class charT, class InputIterator = std::istreambuf_iterator<charT> >
class num_get_strictsignedness : public std::num_get <charT, InputIterator>
{
public:
    typedef charT char_type;
    typedef InputIterator iter_type;

    explicit num_get_strictsignedness(std::size_t refs = 0)
        : std::num_get<charT, InputIterator>(refs)
    {}
    ~num_get_strictsignedness()
    {}

private:
    #define DEFINE_DO_GET(TYPE) \
        virtual iter_type do_get(iter_type in, iter_type end,      \
            std::ios_base& str, std::ios_base::iostate& err,       \
            TYPE& val) const override                              \
        {  return do_get_templ(in, end, str, err, val);  }         // MACRO END

    DEFINE_DO_GET(unsigned short)
    DEFINE_DO_GET(unsigned int)
    DEFINE_DO_GET(unsigned long)
    DEFINE_DO_GET(unsigned long long)

    // not sure if a static locale::id is required..

    template <class T>
    iter_type do_get_templ(iter_type in, iter_type end, std::ios_base& str,
                           std::ios_base::iostate& err, T& val) const
    {
        using namespace std;

        if(in == end)
        {
            err |= ios_base::eofbit;
            return in;
        }

        // leading white spaces have already been discarded by the
        // formatted input function (via sentry's constructor)

        // (assuming that) the sign, if present, has to be the first character
        // for the formatting required by the locale used for conversion

        // use the "C" locale; could use any locale, e.g. as a data member

        // note: the signedness check isn't actually required
        //       (because we only overload the unsigned versions)
        bool do_check = false;
        if(std::is_unsigned<T>{} && *in == '-')
        {
            ++in;  // not required
            do_check = true;
        }

        in = use_facet< num_get<charT, InputIterator> >(locale::classic())
                 .get(in, end, str, err, val);

        if(do_check && 0 != val)
        {
            err |= ios_base::failbit;
            val = 0;
        }

        return in;
    }
};
Run Code Online (Sandbox Code Playgroud)

使用示例:

#include <sstream>
#include <iostream>
int main()
{
    std::locale loc( std::locale::classic(),
                     new num_get_strictsignedness<char>() );
    std::stringstream ss("-10");
    ss.imbue(loc);
    unsigned int ui = 42;
    ss >> ui;
    std::cout << "ui = "<<ui << std::endl;
    if(ss)
    {
        std::cout << "extraction succeeded" << std::endl;
    }else
    {
        std::cout << "extraction failed" << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 不需要在自由存储上进行分配,您可以使用例如(静态)局部变量,在构造1函数中初始化引用计数器
  • 对于您想要支持的每种字符类型(例如,,,char),您需要添加自己的方面(可以是模板的不同实例)wchar_tcharXY_tnum_get_strictsignedness
  • "-0"被接受