在 Windows 上的 C++ 中获取当前用户名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11587426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get current username in C++ on Windows
提问by Andrew
I am attempting to create a program that retrieves the current user's username on Windows using C++.
我正在尝试创建一个程序,该程序使用 C++ 在 Windows 上检索当前用户的用户名。
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?
获取当前用户名的最简单、最好的方法是什么?
回答by orlp
Use the Win32API GetUserName
function. Example:
使用 Win32APIGetUserName
函数。例子:
#include <windows.h>
#include <Lmcons.h>
char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
回答by jyz
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
我正在使用 Visual Studio Express 2012(在 Windows 7 上),也许它与 Dev-Cpp 的工作方式相同
回答by parapura rajkumar
On windows use USERNAMEenviroment variable or GetUserNamefunction
在 Windows 上使用USERNAME环境变量或GetUserName函数
回答by Anna Eurich
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";
}
回答by Van Zuzu
You should use the env variable USERNAME.
您应该使用环境变量 USERNAME。