**No direct answers or code examples please, this is my homework which i need to learn from. I’m looking for help concerning the algorithm i need to develop.
I seem to be having a logic error in coming up with a solution for a portion of my class work, the program involves multiple files, but here is the only relevant portion:
I have a file PlayerStats that holds the stats for a basketball player in:
- rebounds
- points
- assists
- uniform #
my initial reaction would be to create a while loop and read these into a temporary struct that holds these values, then create a merge function that merges the values of the temp struct with the inital array of records, simple enough?
struct Baller
{
//other information on baller
int rebounds;
int assists;
int uniform;
int points;
void merge(Baller tmp); //merge the data with the array of records
}
//in my read function..
Baller tmp;
int j = 0;
inFile << tmp.uniform << tmp.assists << tmp.points << tmp.rebounds
while(inFile){
ArrayRecords[j].merge(tmp);
j++;
//read in from infile again
}
The catch:
The file can have an arbitrary number of spaces between the identifiers, and the information can be in any order(leaving out the uniform number, that is always first). e.g.
PlayerStats could be
11 p3 a12 r5 //uniform 11, 3 points 12 assists 5 rebounds
//other info
OR
11 p 3 r 5 a 12 //same exact values
What I’ve come up with
can’t seem to think of an algorithm to grab these values from the file in the correct order, i was thinking of something along these lines:
inFile << tmp.uniform; //uniform is ALWAYS first
getline(inFile,str); //get the remaining line
int i = 0;
while(str[i] == " ") //keep going until i find something that isnt space
i++;
if(str[i] == 'p') //heres where i get stuck, how do i find that number now?
else if(str[i] == 'a')
eles if(str[i] = 'r'
If you’re only going to check one letter, you could use a
switchstatement instead ofif / else, that would make it easier to read.You know where the number starts at that point, (hint:
str[i+1]), so depending on what type yourstr[]is, you can either useatoiif its a char array, orstd::stringstreamif it’s anstd::string.I’m tempted to give you some code, but you said not too. If you do want some, let me know and I’ll edit the answer with some code.
Instead of using a ‘merge’ function, try using an
std::vectorso you can justpush_backyour structure instead of doing any ‘merging’. Besides, your merge function is basically a copy assignment operator, which is created by the compiler by default (you don’t need to create a ‘merge’ function), you just need to use=to copy the data across. If you wanted to do something special in your ‘merge’ function, then you should overload the copy assignment operator instead of a ‘merge’ function. Simples.