Reputation: 11
The program that I will be creating will get the currently logged in username on the UNIX/Linux system and display a welcome message. What the code blow is doing is executing only this:
Welcome user@hostname:~/Dev/cpp$
The rest of the stream is not outputted. What do I need to do to be able to output the rest of it? Should I use some other function instead of this one? I'm not sure I should even use getenv() for this.
I suppose I could use regex or something to get only the username, but that doesn't solve the problem though the rest of the stream is not outputted anyway.
#include <iostream>
#include <stdlib.h>
int main() {
std::cout << "Welcome " << getenv("USERNAME") << " to APP_NAME. To get available commands use --help" << std::endl;
return 0;
}
Upvotes: 0
Views: 78
Reputation: 25439
The problem is that you're executing the program in an environment where the USERNAME
variable is not set (which does not surprise me). Therefore std::getenv
return
s a nullptr
and streaming this unchecked to std::cout
gives undefined behavior which, in your case, happens to truncate the stream. The user@hostname:~/Dev/cpp$
you're seeing is not produced by your program but your ordinary shell prompt that ends up in a funny position because the program ended abruptly without outputting a final new-line.
You should test the return
value before using it.
#include <cstdlib>
#include <iostream>
int
main()
{
if (const auto user = std::getenv("USERNAME"))
std::cout << "Hello, " << user << "\n";
else
std::cout << "Hello, whoever you may be.\n";
}
Anyway, this is not how you're supposed to obtain the user name of the currently logged in user. If you want to use the environment (which is not reliable) you should use the USER
variable instead. A probably more robust solution would be to use the getlogin
function specified by POSIX and provided via <unistd.h>
. Note that getlogin
may also fail (return
a nullptr
) so you should still have a backup strategy.
Upvotes: 2
Reputation: 149075
The only possible cause is that the environment variable USERNAME
does not exist when you execute your program. The getenv
function returns then a nullptr
(as suggested by @5gon12eder) and you invoke undefined behaviour by injecting a nullptr
in an output stream. In your example, it just ends the output (like if it was inserting a null in a string), in my own one, if raises a SIGSEGV.
You should ensure that the environment variable exists:
int main() {
const char *name = getenv("USERNAME");
if (name == std::nullptr) { name = "unknown guest"; }
std::cout << "Welcome " << name << " to APP_NAME. To get available commands use --help" << std::endl;
return 0;
}
Upvotes: 1