Get current username in C++ on Windows

偶尔善良 提交于 2019-11-27 02:39:59

问题


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?


回答1:


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);



回答2:


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




回答3:


On windows use USERNAME enviroment variable or GetUserName function




回答4:


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";
}



回答5:


You should use the env variable USERNAME.



来源:https://stackoverflow.com/questions/11587426/get-current-username-in-c-on-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!