Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,227 questions

56,129 answers

573 users

How to get the country name from the 2-letter country code (alpha-2) in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm> // transform

// ------------------------------------------------------------
// getCountryName
// Receives a 2-letter ISO country code and returns the
// corresponding country name.
//
// Uses an unordered_map for O(1) average lookup time.
// Input is normalized to uppercase to ensure consistent matching.
// Returns an empty string if the code is not found.
// ------------------------------------------------------------
std::string getCountryName(const std::string& alpha2)
{
    // Static map: initialized once, reused efficiently
    static const std::unordered_map<std::string, std::string> countryMap = {
        {"US", "United States"},
        {"GB", "United Kingdom"},
        {"FR", "France"},
        {"DE", "Germany"},
        {"CA", "Canada"},
        {"JP", "Japan"},
        {"CN", "China"},
        {"IN", "India"}
        // Add more as needed
    };

    // Normalize input: trim not needed here, but uppercase is essential
    std::string code = alpha2;
    std::transform(code.begin(), code.end(), code.begin(), ::toupper);

    // Lookup
    auto it = countryMap.find(code);
    return (it != countryMap.end()) ? it->second : "";
}

// ------------------------------------------------------------
// main
// Demonstrates the lookup function with several sample codes.
// ------------------------------------------------------------
int main()
{
    std::string codes[] = {"US", "GB", "FR", "JP", "ZZ"}; // ZZ is intentionally invalid

    for (const auto& code : codes)
    {
        std::string name = getCountryName(code);

        if (!name.empty()) {
            std::cout << code << " → " << name << "\n";
        }
        else {
            std::cout << code << " → (invalid code)\n";
        }
    }
}


/*
run:

US → United States
GB → United Kingdom
FR → France
JP → Japan
ZZ → (invalid code)

*/

 



answered Jun 17 by avibootz
edited 1 day ago by avibootz
...