Reputation: 61
For my assignment, it says that I am to use the command line argument ./a.out user1.txt (the text file name can change) in my main.cpp.
I have the following in my main.cpp
int main(int argc, char* argv[]){
string name;
name = argv[1];
}
but don't know how I can get name into my BBoard setup function in BBoard cpp
#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);
}
}
with BBoard header here
#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
Edit: How do I use an object in main cpp to send over name to my BBoard function? When I try including main cpp into my board cpp, I get errors.
Upvotes: 0
Views: 445
Reputation: 20047
You're so close. You simply need to edit your main()
function to create a BBoard
object, and pass the name
to it the same way you pass argv[1]
to std::string
. You can then call functions on that object, or pass that object to other functions.
Style advice:
What should happen if somebody forgets to pass the filename to the program? As it stands, you crash. It's pretty easy to tell the user what's wrong and bail if argc
is only 1:
if (argc == 1) {
cout << "usage: a.out file.txt\n";
return 1;
}
Not all programmers use using namespace std
. There's nothing wrong with doing so in .cpp
files, but I personally get upset when #include
-ing a header file has the effect of calling using namespace XXX
for me without my consent. As it is, your header file already fully qualifies things in the To keep me from getting upset when I use your header, you simply need to remove std
namespace, so you can remove that line from your header without needing to make other changes.using namespace std
from the header and use std::vector
instead of simply vector
.
Upvotes: 1
Reputation: 317
What about creating an BBoard
and then calling the setup
function:
if (argc > 1) {
string name = argv[1];
BBoard board;
board.setup(name);
}
Upvotes: 1