2017-06-17 52 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; 
} 
相關問題