3

I am using std::iswalpha to check if a non-ASCII character (French character) is alphabetic. However, I have found that it returns false for é character. I have set my locale to fr_FR.UTF-8 in my code. Can you help me understand why this is happening and how I can correctly determine whether a French character is alphabetic using C++?

#include <iostream>
#include <cwctype>

int main() {
    std::setlocale(LC_ALL, "fr_FR.UTF-8");
    wchar_t ch = L'é';
    bool is_alpha = std::iswalpha(ch);
    std::cout << is_alpha << std::endl; // print 0
    return 0;
}
Abdo21
  • 498
  • 4
  • 14

1 Answers1

4

It's because installing the locale fails, but you don't check that.

Running this in Compiler Explorer prints locale: No such file or directory while running it on my local computer where I have the fr_FR.UTF-8 locale installed succeeds and prints 1:

#include <cstdio>
#include <cwctype>
#include <iostream>

int main() {
    if (std::setlocale(LC_ALL, "fr_FR.UTF-8") == nullptr) {
        std::perror("locale");
    } else {
        wint_t ch = L'é';
        bool is_alpha = std::iswalpha(ch);
        std::cout << is_alpha << std::endl;  // print 1
    }
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
  • Thank you for your answer. Is there an alternative method to check if a non-ASCII character is alphabetic in C++, without relying on a specific locale to be pre-installed? I plan to use this code in an Android device with the NDK, and I am unsure how to require a specific locale on that device. – Abdo21 Feb 16 '23 at 23:34
  • 2
    @Abdo21 Android has ICU library. You can use it. – sklott Feb 16 '23 at 23:39