The function getlogin_r() defined in unistd.h returns the username. See man getlogin_r for more information.
Its signature is:
int getlogin_r(char *buf, size_t bufsize);
Needless to say, this function can just as easily be called in C or C++.