Get current username in C++ on Windows
Use the Win32API GetUserName
function. Example:
#include <windows.h>
#include <Lmcons.h>
char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
How do I get the current username in .NET using C#?
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
Get current user name under Windows
You can use GetUserName
#include <windows.h>
#include <Lmcons.h>
char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
C++ Microsoft example to get and display the user name doesn't compile
Win32 API provide what you need. The function GetUserNameW and GetComputerNameW are exactly what you need and the usage is very simple. Here a example that works:
#include <iostream>
#include <string>
#include <windows.h>
#include <Lmcons.h>
std::wstring getUsername() {
wchar_t username[UNLEN + 1];
DWORD username_len = UNLEN + 1;
GetUserNameW(username, &username_len);
return username;
}
std::wstring getComputerName() {
wchar_t computerName[UNLEN + 1];
DWORD computerName_len = UNLEN + 1;
GetComputerNameW(computerName, &computerName_len);
return computerName;
}
int main()
{
std::wcout << L"Username is : " << getUsername() << std::endl;
std::wcout << L"Computer name is : " << getComputerName() << std::endl;
return 0;
}
Related Topics
Std::Map Default Value for Build-In Type
How to Select a Random Element in Std::Set
Undefined Behavior Causing Time Travel
Opencv How to Select a Region of Image Irregularly with Mouse Event? C/C++
Why Would Anyone Use Set Instead of Unordered_Set
Where Are the Man Pages for C++
What Exactly Is or Was the Purpose of C++ Function-Style Casts
Somehow Register My Classes in a List
Why the Sizeof(Bool) Is Not Defined to Be One, by the Standard Itself
Inverse Fourier Transformation in Opencv
How to Serialize Boost::Dynamic_Bitset