#include#include int main() { char username[UNLEN+1]; DWORD username_len = UNLEN+1; if (!GetUserName(username, &username_len)) { std::cout << "Failed to get username\n"; return 1; } std::cout << "Username: " << username << '\n'; return 0; }
#includeThis example extends on the previous one by adding error handling. In case GetUserName fails, it retrieves the last error code using GetLastError and formats it into a human-readable string using FormatMessageA. Package Library: The package library for GetUserName is the Windows API, which is included in the Windows operating system. Therefore, no additional package needs to be installed to use it.#include int main() { char username[UNLEN+1]; DWORD username_len = UNLEN+1; if (!GetUserName(username, &username_len)) { DWORD error = GetLastError(); LPSTR error_msg; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, nullptr, error, 0, (LPSTR)&error_msg, 0, nullptr ); std::cout << "Failed to get username: " << error_msg << '\n'; LocalFree(error_msg); return 1; } std::cout << "Username: " << username << '\n'; return 0; }