简体   繁体   English

“ctype”的功能来自 <locale> 抛出一个std :: bad_cast

[英]“ctype” functions from <locale> throw an std::bad_cast

This program 这个计划

#include <iostream>
#include <locale>

int main () {
    std::isxdigit(std::cin.peek(), std::cin.getloc());
}

throws an exception of type std::bad_cast on me when compiled with gcc or clang using libstdc++. 当使用libstdc ++使用gcc或clang编译时,会抛出类型为std::bad_cast的异常。 It runs normally with VS2010. 它与VS2010一起正常运行。

I understand what's going on here. 我明白这里发生了什么。 peek() returns an int to accommodate the out-of-band EOF value. peek()返回一个int以适应带外EOF值。 The locales are not required to have ctype<int> facet (they do have this facet in VS, perhaps as an extension). 语言环境不需要具有ctype<int> facet(它们在VS中具有此方面,可能作为扩展)。 If the locale has no facet to perform a function, it will throw a bad_cast . 如果语言环境没有facet来执行函数,它将抛出bad_cast

But shouldn't this be working according to the spirit of the original <ctype.h> ? 但是这不应该按照原来的<ctype.h>的精神工作吗? Is this a defect in the standard? 这是标准中的缺陷吗? Is there a commonly-accepted workaround? 有一个普遍接受的解决方法吗? I know I can check for EOF myself and cast to the relevant character type, but I'd rather not reinvent the wheel. 我知道我可以自己检查EOF并投射到相关的角色类型,但我宁愿不重新发明轮子。

No: The character type has to be known (assume a 32 bit int is a character type having a 64 bit representation for EOF). 否:必须知道字符类型(假设32位int是具有64位EOF表示的字符类型)。 It can not be resolved, a locale is not bounded to a specific character type, but it's facets are. 它无法解决,区域设置不受特定字符类型的限制,但它的方面是。

Having: 有:

std::isxdigit<char>(std::cin.peek(), std::cin.getloc());

will clarify the call and (!) ignore EOF making it char(int(-1)). 将澄清调用和(!)忽略EOF使其成为char(int(-1))。

Hence you might check for EOF yourself. 因此,您可以自己检查EOF。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM