Search code examples
c++consolelocalecinsetlocale

How to change locale for cin


I have two languages in my Ubuntu. And I want to start my simple program but need to enter the data in different languages. I am tired to switch global toggle from one lang to another. And now I am trying to automate this process by following code:

#include <locale>
#include <clocale>
void change_locale(bool lang)
{
    std::locale delocale("de_DE.utf8");
    std::locale enlocale("en_AG");

    if (lang == true){
        std::cout << "set DE locale" << '\n';
        setlocale(LC_ALL,"de_DE.utf8");
        std::locale::global(delocale);
        std::cin.imbue(delocale);
    }
    else {
        std::cout << "set Eng locale" << '\n';
        setlocale(LC_ALL,"en_AG");
        std::locale::global(enlocale);
        std::cin.imbue(enlocale);
    }
}

but it doesn't work. Please pay attention it is applied for cin only. How to make it workable?


Solution

  • finally, found the solution with setxkbmap utility. I've created two scripts where the command is called

    • de.sh file setxkbmap de
    • en.sh file setxkbmap en

    and then call it from the source code

    #include <locale>
    #include <clocale>
    void change_locale(bool lang)
    {
        std::locale delocale("de_DE.utf8");
        std::locale enlocale("en_AG");
    
        if (lang == true){
            setlocale(LC_ALL,"de_DE.utf8");
            std::locale::global(delocale);
            std::cin.imbue(delocale);
            system("de.sh");
        }
        else {
            setlocale(LC_ALL,"en_AG");
            std::locale::global(enlocale);
            std::cin.imbue(enlocale);
            system("en.sh");
        }
    }