GetUserName() returns 1

Hello

I'm trying to get the username of the current user (not computer name). I'm also trying to do this OOP using classes and functions/methods, but it ain't working.

This is my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <windows.h>
#include <Lmcons.h>


using namespace std;

class info {
public:
	TCHAR getName() {
		TCHAR usernameBuffer[UNLEN+1];
		DWORD usernameLength = UNLEN + 1;
		TCHAR username = GetUserName(usernameBuffer, &usernameLength);
		
		return username;
	}
};

int main() {
	info info;
	cout << info.getName();

	cin.ignore().get();
}



The function getName() returns 1, I guess 1 means 'succeeded', but I want the username (variable usernameBuffer), but how exactly would I do that?

Thanks for reading,
Niely
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <windows.h>
#include <lmcons.h>
#include <string>

#pragma comment( lib, "advapi32" )  

std::wstring user_name_w()
{
	wchar_t buffer[UNLEN+1]{};
	DWORD len = UNLEN+1;
	if( ::GetUserNameW(buffer, &len) ) return buffer;
	else return {}; // or: return L"" ;
}

std::string user_name()
{
	char buffer[UNLEN+1]{};
	DWORD len = UNLEN+1;
	if( ::GetUserNameA( buffer, &len ) ) return buffer;
	else return {}; // or: return "" ;
}

int main()
{
	std::wcout << user_name_w() << L'\n';
	std::cout << user_name() << '\n';
}
^Thanks!
I just had to add GetUserName() with GetUserNameA(); why is it working when I add an A?

And I've got another question as well, my code isn't working when I replace DWORD with unsigned int, however, DWORD is the same as a 32-bit unsigned int.
> why is it working when I add an A?

Most Windows API functions and structures involving strings are available in two versions:
a UTF-8 version eg. GetUserNameA(), CreateFileA() etc (xxxnameA)
and a UTF-16 version eg. GetUserNameW(), CreateFileW() etc (xxxnameW)

A name without the suffix A or W maps to either one or the other depending on preprocessor definitions.
More info: https://en.wikibooks.org/wiki/Windows_Programming/Unicode


> my code isn't working when I replace DWORD with unsigned int,
> however, DWORD is the same as a 32-bit unsigned int.

IIRC, on most platforms, DWORD is a type alias for unsigned long.
In C++, unsigned int and unsigned long are two distinct types;
there is no implicit conversion from unsigned int* to unsigned long*
^Okay, thanks!
Thanks for helping me out efficiently and fast!
Topic archived. No new replies allowed.