Get current username in C++ on Windows

Viewed 99089

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?

8 Answers

In case GetUserName(username, &username_len); doesn't work when using a char[] as storage, you should know that GetUserName could be a macro solved to GetUserNameW. If u worked with Windows API probably u know the difference between W and A. Using GetUserNameA would solve the problem if you're using char[] as buf

By using getenv() function:

char * user = getenv("username");
cout << string(user) << endl;

If you want to convert into string then use:

string userStr = string(user);
void funtions::_GetUserNameA()

char username[1024];
DWORD username_len = 1024;
GetUserNameA(username,&username_len);
std::cout <<"username:"<< username <<"\n";
Related