1

I'm relatively new to WinAPI programming in C++. I'm trying to write a program that will obtain the system hostname using GetComputerName(). Ideally, I want the code to be able to work on English and non-English systems. Below is the code that I'm using:

int main()
{
    wstring hostname;
    wchar_t nbtName[MAX_COMPUTERNAME_LENGTH + 1];
    DWORD length = MAX_COMPUTERNAME_LENGTH + 1;
    GetComputerName(nbtName, &length);
    hostname = nbtName;

    wcout << hostname << endl;

    return 0;
}

The code works fine on my English Windows 7 system, but the code doesn't seem to display properly on my German Windows 7 system (which uses German characters for the hostname). I thought that wstring and wchar_t could handle these special characters. Here's what's displayed on my German Windows 7 system.

COMPUTER-Í─▄▀

Am I overlooking something stupid? Thanks!

t3ntman
  • 163
  • 3
  • 11
  • Can you copy/paste the name into the console successfully? Perhaps the console is using a font which has different glyphs for the required code-points. – enhzflep Apr 10 '16 at 03:26
  • If I use the Windows "hostname" command, the German characters show up correctly. – t3ntman Apr 10 '16 at 03:38

3 Answers3

4

Use _setmode(_fileno(stdout), _O_U16TEXT) to show Unicode in console window:

#include <iostream>
#include <string>
#include <io.h> //for _setmode
#include <fcntl.h> //for _O_U16TEXT

int main()
{
    _setmode(_fileno(stdout), _O_U16TEXT);
    std::wcout << L"ελληνικά\n";
    return 0;
}

Or use MessageBoxW(0, hostname.c_str(), 0, 0) or OutputDebugStringW to see Unicode text displayed correctly:

Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77
1

this function has two versions GetComputerNameW for unicode and GetComputerNameA for ANSI. if UNICODE is defined in your environment the the first one will be called. So either make sure UNICODE is defined or try to call the GetComputerNameW directly.

Biruk Abebe
  • 2,235
  • 1
  • 13
  • 24
  • Unicode is defined in my project. I tried the GetComputerNameW() function instead of the GetComputerName() but the issue is still the same. – t3ntman Apr 10 '16 at 04:46
  • @t3ntman Then maybe your problem is your console output not displaying Unicode characters properly. there is a discussion about that [here](http://stackoverflow.com/questions/28216113/unicode-output-on-windows-console?rq=1) – Biruk Abebe Apr 10 '16 at 04:54
  • I'll investigate it, but I find it strange that the native Windows executable like "hostname" would display the correct hostname, but my program does not. – t3ntman Apr 10 '16 at 04:59
0

Windows Console output was the culprit. The Unicode characters display correctly in other non-console output. Thanks everyone!

t3ntman
  • 163
  • 3
  • 11