Need help with string and system()

I'm trying to use use system() to find the user's name, and set it as a string but it's not working. An example of what I'm trying to do is:

#include <iostream>
using namespace std;

int main() {
string user = system("echo %USERNAME%");

cout << "Hello, " << user;
};
The return of system is implementation-defined, but it's returning an int, not a string, and isn't copying the standard output (the echo output).

If you need to get system information like the current user name, I suggest using the API of the system you're on. What OS are you running?

Edit: Oh it's Windows obviously from the %TOKEN% syntax.

Try: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getusernamea

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <iostream>
#include <windows.h>

// https://docs.microsoft.com/en-us/windows/win32/sysinfo/getting-system-information
int main()
{
    const DWORD buffer_size = 256 + 1; // AKA: UNLEN + 1
    TCHAR infoBuf[buffer_size];
    DWORD bufCharCount = buffer_size;
    
    int ret = GetUserNameA(infoBuf, &bufCharCount);
    
    if (!ret)
    {
        int err = GetLastError();
        std::cout << "error " << err << "\n";
    }
    else
    {
        std::cout << infoBuf << '\n';
    }  
}


__________________________________

Note, infoBuf is of course not a string, it's a null-terminated TCHAR array.
If unicode is enabled (the default I believe), then this is convertible to a std::wstring.

See:
https://stackoverflow.com/questions/6006319/converting-tchar-to-string-in-c/28177280
https://stackoverflow.com/questions/6291458/how-to-convert-a-tchar-array-to-stdstring
Last edited on
Another way is to use std::getenv, if you're sure you just want whatever %USERNAME% is (Another program might modify your environmental variable, so in general it's not as secure).

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>
#include <cstdlib>

int main()
{
    // https://en.cppreference.com/w/cpp/utility/program/getenv
    std::string username = std::getenv("USERNAME");
    std::cout << username << '\n';
}
Last edited on
Thank you Ganado! The name is now stored as a variable and is now able to output properly.
Topic archived. No new replies allowed.