Search code examples
c++graphicsinternationalizationproject

Multilingual C++ program


How can I add multilanguage support to a C++ program? I want to let the user to choose between 2 languages when opening the app. What's the simplest way without any external libraries?


Solution

  • Replying to my comment, "You could make a dictionary where it's key is an enum representing a word, then the values could be an array of structures containing the language and actual string in that language. Example: (pseudo code) dictionary: - WORD1_ENUM => structure[LANGUAGE1_ENUM, WORD_IN_LANGUAGE1], structure[LANGUAGE2_ENUM, WORD_IN_LANGUAGE2]", you could make a dictionary that retrieves your world based on the selected language.

    #include <initializer_list>
    #include <string>
    #include <vector>
    #include <iostream>
    
    
    enum STRINGS
    {
        HELLO_WORLD,
        GOODBYE_WORLD
    };
    
    #define SELECTED_LANGUAGE SLOVENIAN
    #define NOT_FOUND_STR  "Not Found"
    enum LANGUAGE
    {
        ENGLISH,
        SLOVENIAN
    };
    
    
    struct DICTIONARY_VAL
    {
        LANGUAGE lang;
        std::string text;
    };
    
    struct DICTIONARY_BLOCK_t{
        STRINGS key;
        std::vector<DICTIONARY_VAL> values;
    };
    
    
    class DICTIONARY_t
    {
    private:
        std::vector<DICTIONARY_BLOCK_t> data;
    public:
        DICTIONARY_t (std::initializer_list<DICTIONARY_BLOCK_t> var)
        {
            for (DICTIONARY_BLOCK_t val : var)
            {
                data.push_back(val);
            }
        }
    
        std::string get_value(STRINGS key, LANGUAGE lang)
        {
            std::string l_ret = NOT_FOUND_STR;
            for (uint32_t i = 0; i < data.size() ; i++)
            {
                if (data[i].key == key)
                {
                    for (uint32_t j = 0; j < data[i].values.size(); j++)
                    {
                        if (data[i].values[j].lang == lang)
                        {
                            l_ret = data[i].values[j].text;
                            break;
                        }
                    }
                    break;
                }
            }
            return l_ret;
        }
    
    };
    
    DICTIONARY_t dict = 
    {
        {HELLO_WORLD,   { {ENGLISH, "Hello World"},   {SLOVENIAN, "Zivjo svet"     }  }},
        {GOODBYE_WORLD, { {ENGLISH, "Goodbye World"}, {SLOVENIAN, "Nasvidenje svet"}  }}
    };
    
    
    
    int main()
    {
        LANGUAGE selected_language;
        std::cout << "Select your lanugage\n0.) ENGLISH\n1.) Slovenian" << std::endl;
        int tmp;
        std::cin >> tmp;
        selected_language = (LANGUAGE) tmp;
    
        
        std::cout << dict.get_value(HELLO_WORLD, selected_language) << std::endl;
    
    
        return 0;
    }