Get current username in C++ on Windows

流过昼夜 提交于 2019-11-28 09:07:04

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.

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