生成std::isalpha求值为true的范围

generate range for which std::isalpha evaluates to true

本文关键字:true 范围 std isalpha 生成      更新时间:2023-10-16

对于某些人来说,这可能是一个微不足道的问题,但我找不到合适的答案。我想要的是生成一个范围(假设是一个std::string),它包含所有可能的char s,其中std::isalpha的计算结果为true

例如,对于默认的区域设置,字符串应该是"A...Za...z"。但是,如果语言环境是法语,那么重音字母也应该属于字符串。

PS:我从Dieter l cking那里得到了一个解决方案,https://stackoverflow.com/a/25125871/3093378它似乎在所有平台上工作,除了我的(OS X 10.9.4 g++4.9, clang++ LLVM版本5.1 (clang-503.0.40)),当试图访问table[i]

行时,它只是分段错误
if(table[i] & ctype::alpha)

我想知道是否有人能在Mac或任何其他平台上重现这个错误。

您可以直接使用ctype-table,而不是按照字母顺序生成一组字符来对字符进行分类:

#include <iostream>
#include <locale>
int main() {
    typedef std::ctype<char> ctype;
    std::locale locale;
    const ctype& facet = std::use_facet<ctype>(locale);
    const ctype::mask* table = facet.table();
    // You might skip this and work with the table, only.
    std::string result;
    for(unsigned i = 0; i < facet.table_size; ++i) {
        if(table[i] & ctype::alpha)
            result += char(i);
    }
    std::cout << result << 'n';
    return 0;
}

如果你需要一个可移植的解决方案,那么我想不出任何理由在所有可能的char值上运行isalpha()不是你的最佳选择。

如果平台特定的方法是可接受的,那么您可以从平台的语言环境定义中提取信息。这里有一些文档可以帮助您开始使用POSIX平台:http://pubs.opengroup.org/onlinepubs/009696699/basedefs/xbd_chap07.html