Im trying to write a program that will read a file and set a name and the 5 votes the person casts. The problem is that the fstream is not reading the file correctly. However if I open another object in the main the method they both print perfectly.
I've tryed looking at similar issues but none seem to fix it.
#include <iostream>
#include <fstream>
using namespace std;
class pledge {
public:
string name;
string *vote;
void setName(string n) {name = n;}
void setVote(string *v) {vote = v;}
void printName() {cout << name << endl;}
void printVote();
void print();
};
void pledge::printVote() {
cout << vote[0] << endl;
cout << endl;
}
void pledge::print() {
cout << name << ": ";
for (int i = 0; i < 5; i++) {
cout << vote[i] << ", ";
}
cout << endl;
}
pledge* createPledges(char[], int);
int main(int agrc, char *argv[]) {
int n;
n = stoi(argv[2]);
pledge *p = createPledges(argv[1], n);
cout << p -> vote[0] << endl;
}
pledge* createPledges(char filename[], int n) {
fstream input;
input.open(filename);
pledge* p = new pledge();
string name, vote[5];
getline(input, vote[0]);
p -> setVote(vote);
return p;
}
One of the biggest reasons that
fstreamis not working is because thevotesarray is not implemented correctly. This answer gives a few tips on how to correct that.I am going to assume that this is a homework assignment, and also that you have no experience with some of the advanced (and not-so-advanced) C++ features that could make the assignment easier.
std::vectorstd::arrayoperator<<andoperator[]throwOkay, so use a built-in array to hold votes. Do not use a pointer.
Suppose you want two constructors, one that takes a name only, and another which takes a name, and an array of five votes. The first one should be easy enough, but the second will require copying the array of votes. You have to pass the array (and its size), and then run a loop to do the copying.
Here is an example that is careful to match size of the array that is passed into the constructor against the size of the array stored in a
Pledge. If they are not the same, it avoids accessing any out-of-range elements.This works, and might be worth keeping, but I have another idea. What if we just hard-code the five votes into the constructor? It's almost like cheating, but the code is stupid-simple.
Next, we should take a look at the set and get routines used for votes. They should accept a subscript as an argument, and check to make sure it is not out-of-range.
You pretty much have the print routines covered. Just two tips:
print_name, followed byprint_votes, and let them do the work.I think you should do a complete rewrite of function
createPledges(or even delete it). I would start by coding a function that reads exactly onePledgeand his five votes, and then returns it directly. Do not use any pointers or operatornew.I have left many details incomplete. That is intentional. This should give you a good start, but I want to let you have some of the fun, too!