8
I am developing an application and in one of its methods accurate capture the name of the computer and the user logged into the machine, then present on screen to the user. What’s the best way to do that?
8
I am developing an application and in one of its methods accurate capture the name of the computer and the user logged into the machine, then present on screen to the user. What’s the best way to do that?
9
In environment Windows you can use getenv("COMPUTERNAME")
, getenv("USER")
.
In Linux - getenv("HOSTNAME")
, getenv("USER")
.
See also the reference getenv
.
1
Complementing the above answer,
getenv()
returns:
C String
with the value of the requested environment variable, orThe linux
sets the environment variable that stores the username as $USER, so to use the function in the linux
to obtain the current user name,
do getenv("USER")
.
The windows
does not have a "USER" environment variable, but yes, "USERNAME", which returns the same thing (the username), so to use the function in the windows
, do getenv("USERNAME")
.
You can type "set" in a console/terminal/prompt window and see all currently configured environment variables on windows
. There you should find "USERNAME" instead of "USER".
In the linux
, if you type "env" in the terminal, you will see that there is a "USER" variable, keeping the name of the current user.
getenv()
is defined in cstdlib/stdlib.h
Example:
#include <iostream>
#include <cstdlib>
int main(){
/*Para obter o nome de usuário no linux*/
#ifdef __linux__
std::cout << "O nome do usuário atual é: " << getenv("USER") << std::endl;
#endif
/*Para obter o nome de usuário no windows*/
#ifdef _WIN32
std::cout << "O nome do usuário atual é: " << getenv("USERNAME") << std::endl;
#endif
}
Browser other questions tagged c++
You are not signed in. Login or sign up in order to post.