Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current username in C++ on Windows

Tags:

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?

like image 910
Andrew Avatar asked Jul 20 '12 21:07

Andrew


People also ask

How to Get current user name in Windows?

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.

How to Get username in Windows c++?

char *userName = getenv("LOGNAME"); stringstream ss; string userNameString; ss << userName; ss >> userNameString; cout << "Username: " << userNameString << endl; Nothing is outputted except "Username:".

How do I get the current username in .NET using C#?

GetCurrent(). Name; Returns: NetworkName\Username.


2 Answers

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); 
like image 115
orlp Avatar answered Sep 18 '22 18:09

orlp


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

like image 25
jyz Avatar answered Sep 16 '22 18:09

jyz