I am attempting to create a program that retrieves the current user's username on Windows using C++.
I tried this:
char *userName = getenv("LOGNAME"); stringstream ss; string userNameString; ss << userName; ss >> userNameString; cout << "Username: " << userNameString << endl;
Nothing is outputted except "Username:".
What is the simplest, best way to get the current username?
In the box, type cmd and press Enter. The command prompt window will appear. Type whoami and press Enter. Your current user name will be displayed.
char *userName = getenv("LOGNAME"); stringstream ss; string userNameString; ss << userName; ss >> userNameString; cout << "Username: " << userNameString << endl; Nothing is outputted except "Username:".
GetCurrent(). Name; Returns: NetworkName\Username.
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);
Corrected code that worked for me:
TCHAR username[UNLEN + 1]; DWORD size = UNLEN + 1; GetUserName((TCHAR*)username, &size);
I'm using Visual Studio Express 2012 (on Windows 7), maybe it works the same way with Dev-Cpp
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With