How get user name


Hi,

Can somebody, write a simple code on how to get user name using this
function GetUserName it must include windows.h , I try it to understand, but
didn't find good explanation on the internet.

Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#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 ))
    cout << "Hello, " << name << "!\n";
  else
    cout << "Hello, unnamed person!\n";

  return 0;
  }

Hope this helps.

[edit] Modified to use TCHAR for unicode...
Last edited on

It didnt work.
I get this error:

Error 1 error C2664: 'GetUserNameW' : cannot convert parameter 1 from 'char [257]' to 'LPWSTR' c:\documents and settings\administrator\my documents\visual studio 2005\projects\jasmin_mahmutovic\jasmin_mahmutovic\main.cpp 14

Code works fine. Look at your error it has 'GetUserNameW << maybe thats the problem?
Are you trying to get the user name in wide characters? If so, you should change the type of name to wchar_t (wchar_t name[UNLEN+1];) and then, while calling the function cast it to LPWSTR:
GetUserNameW( (LPWSTR)name, &size )
Last edited on
I just copy/paste your code , and get that error.
----------------------------------------------------- It work when I compile it in DEV++ , but dont work in visual studio 2005 Any sugestion,

-----------------------------------------------------
Can this be fixed.
Last edited on
Read the Error description , it tells you the solution !
=> You're compiling in UNICODE.

The solution is:

[Project] [Properties] [Configuration Properties] [General]
[Character Set] => Use Multi-Byte Character Set
I tried copy / pasting this code but the result came out is:

Hello, 0012FD5C


Any help? =\
Argh, I think I see a bug in my code. You're compiling with UNICODE, right? Try

13 wcout << L"Hello, " << name << L"!\n";

(I think that will work...)
Last edited on
It did, thanks. :)
Topic archived. No new replies allowed.