2017-06-17 74 views
-1

O.K.所以我想要做的是创建一个名为greeter的类,让它获得当前用户名,然后将它传递给一个函数,说“你好(用户名)”。C++在类中获取用户名并将其传递给函数

我到目前为止是这样的:

#include <iostream> 
#include <string> 

using namespace std; 


class greet 
    { 
    public: 

    void hello(string name) 
    { 
    cout << "Hello, " + name + "!" << endl; 
    } 
    }; 

    int main() 
     { 
     greet user; 
     user.hello(name); 
     return 0; 
     } 

“名”是origionally会作为一个参数来自用户的输入来,但

user.hello() 

直接传递给函数不会接受变量“名称”,我宁愿程序无论如何都得到它自己的用户名。所以我的问题是如何让C++自己获取用户名并将其从变量传递到user.hello()

+0

你靶向什么平台?不同的操作系统对用户进行不同的实现,并提供不同的API来查询用户信息。 C++本身或STL没有任何东西可以为你处理。 –

+0

最好是跨平台的解决方案,但我的系统是Linux,因此如果它不能“一刀切”,那么对于Linux。 – Josh

+0

我不是一个实用的项目,只是为了帮助我找出课程 – Josh

回答

1

您可以使用std::getenv来获取当前用户的名称。 Linux的环境变量是"USER"。 Windows的环境变量为"USERNAME"

在Linux上,以下应该工作。

int main() 
{ 
    greet user; 
    char const* name = std::getenv("USER"); 

    // Windows 
    // char const* name = std::getenv("USERNAME"); 

    user.hello(name); 
    return 0; 
} 
+0

错误:名称空间中没有成员“getenv”std – Josh

+0

@Josh,您需要将'#include '添加到您的文件中。 –

+0

感谢建设者(IDE)没有给出任何更多的错误,但gcc说:在函数'int main()':错误:没有匹配函数调用'招呼::你好(const char *&)' user.hello名称); ^ 注:候选人:无效迎接::你好() 无效打招呼() ^ ~~~~ 候选人预计0参数,1提供 – Josh

0
#include <iostream> 
#include <cstdlib> 
#include <string> 

using namespace std; 
class greet 
{ 
    public: 

     void hello(string user) 
     { 
     cout << "Hello, " + user + "!" << endl; 
     } 
}; 

int main() 
{ 
    greet user; 
    char const* USER = std::getenv("USER"); 
    user.hello(USER); 
    return 0; 
} 
0
#include <iostream> 
#include <string> 
#include <cstdlib> 

using namespace std; 

class greet { 
private: 
    string userName() const { 
     static string user = getenv(
      #ifdef WIN32 
      "USERNAME" 
      #else 
      "USER" 
      #endif 
     ); 
     return user; 
    } 

public: 
    void hello() { 
     cout << "Hello, " + userName() << "!" << endl; 
    } 
}; 

int main() { 
    greet user; 
    user.hello(); 
    return 0; 
} 
相关问题