And*_*rew 16 c++ windows dev-c++
我正在尝试创建一个程序,使用C++在Windows上检索当前用户的用户名.
我试过这个:
char *userName = getenv("LOGNAME");
stringstream ss;
string userNameString;
ss << userName;
ss >> userNameString;
cout << "Username: " << userNameString << endl;
Run Code Online (Sandbox Code Playgroud)
除"用户名:"外没有输出任何内容.
获取当前用户名的最简单,最好的方法是什么?
orl*_*rlp 43
使用Win32API GetUserName函数.例:
#include <windows.h>
#include <Lmcons.h>
char username[UNLEN+1];
DWORD username_len = UNLEN+1;
GetUserName(username, &username_len);
Run Code Online (Sandbox Code Playgroud)
更正了适用于我的代码:
TCHAR username[UNLEN + 1];
DWORD size = UNLEN + 1;
GetUserName((TCHAR*)username, &size);
Run Code Online (Sandbox Code Playgroud)
我正在使用Visual Studio Express 2012(在Windows 7上),也许它与Dev-Cpp的工作方式相同
小智 5
有用:
#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";
}
Run Code Online (Sandbox Code Playgroud)