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?
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
On windows use USERNAME enviroment variable or GetUserName function
It works:
#include <iostream>
using namespace std;
#include <windows.h>
#include <Lmcons.h>
int main()
{
TCHAR name [ UNLEN + 1 ];
DWORD size = UNLEN + 1;
if (GetUserName( (TCHAR*)name, &size ))
wcout << L"Hello, " << name << L"!\n";
else
cout << "Hello, unnamed person!\n";
}
You should use the env variable USERNAME.
来源:https://stackoverflow.com/questions/11587426/get-current-username-in-c-on-windows