2014-02-15 228 views
0

對於我的任務,它說我要在main.cpp中使用命令行參數./a.out user1.txt(文本文件名可以更改)。C++的命令行參數?

我有我的main.cpp

int main(int argc, char* argv[]){ 
    string name; 
    name = argv[1]; 
} 

以下,但不知道我怎樣才能名進入BBoard CPP我BBoard設置功能

#include "BBoard.h" 
#include <fstream> 
#include <algorithm> 
using namespace std; 

User user_l; 
BBoard::BBoard(){ 
    title = "Default BBoard"; 
    vector<User> user_list; 
    User current_user; 
    vector<Message> message_list; 
} 

BBoard::BBoard(const string &ttl){ 
    title = ttl; 
} 

void BBoard::setup(const string &input_file){ 
    ifstream fin;; 
    fin.open(input_file); 
    while(!fin.eof()){ 
     user_list.push_back(user_l); 
    } 
} 

與BBoard頭這裏

#ifndef BBOARD_H 
#define BBOARD_H 

#include <iostream> 
#include <string> 
#include <vector> 
using namespace std; 
class User 
{ 
public: 
    User() { } 

    User(const std::string& _name, const std::string& _pass) 
     : name(_name), pass(_pass) 
    { } 

    friend bool operator==(const User& lhs, const User& rhs) 
    { 
     return (lhs.name == rhs.name) && 
       (lhs.pass == rhs.pass); 
    } 
private: 
    std::string name; 
    std::string pass; 
}; 
class Message{ 
}; 
class BBoard{ 
private: 
    string title; 
    vector<User> user_list; 
    User current_user; 
    vector<Message> message_list; 
public: 
    BBoard(); 
    BBoard(const string &ttl); 
}; 

#endif 

編輯:如何使用主cpp中的對象將名稱發送到BBoard函數?當我嘗試將主要cpp包含到我的主板cpp中時,出現錯誤。

+1

另一個祕訣:從不包括源文件;即不會執行'#include「main.cpp」'或類似的操作。 – noobProgrammer

回答

1

你很親密。您只需編輯您的main()函數以創建一個BBoard對象,並將name傳遞給它,就像您將argv[1]傳遞給std::string一樣。然後您可以調用該對象上的函數,或將該對象傳遞給其他函數。


造型建議:

如果有人忘記文件名傳遞給程序應該發生什麼呢?就目前而言,你會崩潰。這是很容易分辨什麼是錯的用戶和保釋如果argc僅爲1:

if (argc == 1) { 
    cout << "usage: a.out file.txt\n"; 
    return 1; 
} 

並非所有的程序員使用using namespace std。在.cpp文件中這樣做沒有任何問題,但是當我在#include中遇到頭文件時,如果未經我的同意,可能會給我打電話using namespace XXX,我個人會感到不安。 事實上,您的頭文件已經完全限定了 std名稱空間中的所有內容,因此您可以從頭中刪除該行而無需進行其他更改。 爲了防止我在使用標題時感到不安,只需從標題中刪除using namespace std,然後使用std::vector而不是簡單地vector

+1

當使用標題中的名稱空間去除時,他仍然需要在std中預先添加向量。 – typ1232

+0

我按照建議進行了編輯,但學校可測試者表示我的BBoard設置功能對於fin.open(input_file)無效;造成問題。我應該在那裏添加const還是其他的東西? –

+0

@ typ1232謝謝,更正。 –

1

什麼有關創建BBoard,然後調用setup功能:

if (argc > 1) { 
    string name = argv[1]; 
    BBoard board; 
    board.setup(name); 
}