There are several issues with the code as posted. The most blatant one is the use of TCHAR
s. TCHAR
was invented, before Win9x had Unicode support, in an attempt to keep code source code compatible between Win9x and Windows NT (the latter uses Unicode with UTF-16LE throughout). Today, there is no reason to use TCHAR
s at all. Simply use wchar_t
and the Windows API calls with a W
suffix.
The C-style casts (e.g. return (TCHAR*)infoBuf
) are another error waiting to happen. If the code doesn't compile without a cast in this case, this means, you are using incompatible types (char
vs. wchar_t
).
Plus, there's a logical error: When using C-style strings (represented through pointers to a sequence of zero-terminated characters), you cannot use operator==
to compare the string contents. It will compare the pointers instead. The solution to this is to either invoke an explicit string comparison (strcmp), or use a C++ string instead. The latter overloads operator==
to perform a case-sensitive string compare.
A fixed version might look like this:
#include <windows.h>
#include <string>
#include <iostream>
#include <stdexcept>
std::wstring getComputerName() {
wchar_t buffer[MAX_COMPUTERNAME_LENGTH + 1] = {0};
DWORD cchBufferSize = sizeof(buffer) / sizeof(buffer[0]);
if (!GetComputerNameW(buffer, &cchBufferSize))
throw std::runtime_error("GetComputerName() failed.");
return std::wstring(&buffer[0]);
}
int main() {
const std::wstring compName = getComputerName();
if ( compName == L"USER" ) {
std::wcout << L"Print your message" << std::endl;
}
}