我正在尝试创build一个程序,它使用C ++在Windows上检索当前用户的用户名。
我试过这个:
char *userName = getenv("LOGNAME"); stringstream ss; string userNameString; ss << userName; ss >> userNameString; cout << "Username: " << userNameString << endl;
除“用户名:”以外不输出任何内容。
获取当前用户名的最简单,最好的方法是什么?
使用Win32API GetUserName
函数。 例:
#include <windows.h> #include <Lmcons.h> char username[UNLEN+1]; DWORD username_len = UNLEN+1; GetUserName(username, &username_len);
在Windows上使用USERNAME环境变量或GetUserName函数
更正的代码,为我工作:
TCHAR username[UNLEN + 1]; DWORD size = UNLEN + 1; GetUserName((TCHAR*)username, &size);
我正在使用Visual Studio Express 2012(在Windows 7上),也许它与Dev-Cpp的工作方式相同
你应该使用env变量USERNAME。
有用:
#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"; }