代码之家  ›  专栏  ›  技术社区  ›  Thomas Matthews

在模板函数中从IStream提取bool

  •  3
  • Thomas Matthews  · 技术社区  · 15 年前

    我正在将字段类读取函数转换为一个模板函数。我有外勤课程 int, unsigned int, long, unsigned long . 它们都使用相同的方法从 istringstream (仅类型更改):

    template <typename Value_Type>
    Value_Type Extract_Value(const std::string& input_string)
    {
        std::istringstream    m_string_stream;
        m_string_stream.str(input_string);
        m_string_stream.clear();
        m_string_stream >> value;
        return;
    }
    

    棘手的部分是 bool (布尔)类型。布尔值有许多文本表示:
    0, 1, T, F, TRUE, FALSE , 以及所有不区分大小写的组合

    问题如下:

    1. C++标准所说的是什么? 要提取的有效数据 布尔 , 使用流提取 操作员?
    2. 因为布尔值可以用 文本,这涉及到 locale S?
    3. 这个平台依赖吗?

    我想通过不为编写自己的处理程序来简化代码 布尔 输入。

    我使用MS Visual Studio 2008(版本9)、C++和WindowsXP和Vista。

    1 回复  |  直到 15 年前
        1
  •  2
  •   MSN    15 年前

    “真”和“假”的字符串由 std::numpunct::truename() std::numpunct::falsename() . 你可以得到 numpunct 对于给定流 use_facet <numpunct <char> >(stream.getloc()) ,如果我正确理解文档。

    编辑:可以切换是否使用 "1" / "0" "true" / "false 具有 std::noboolalpha std::boolalpha .

    推荐文章