2014-02-15 136 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); 
}