I2obiN I2obiN - 18 days ago 5
C++ Question

Printing my Username in VS2015 C++

So I simply want to print my username from the command line variable %username%. This works no problem in cmd.exe if I just:

echo %username%


Now I want to do the same in CPP so I can store it in a string or char array. I'm running Visual Studio 2015

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

int main()
{
TCHAR* username = TEXT("USERNAME = %username%");
cout << username;
return 0;
}


Everytime I build and run the program (through cmd.exe) I get a random username:

013471A0


Tried suggestions on Google to no avail. The username is always random. I'm logged into VS2015, does that have an affect on anything?

Answer

I've found this somewhere here at stackoverflow few weeks ago:

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <lmcons.h>


using namespace std;

int main()
{
    TCHAR UserName[UNLEN + 1];
    DWORD Size = UNLEN + 1;

    GetUserName((TCHAR*)UserName, &Size);
    wcout << UserName;

    int i;
    cin >> i;
}