Reputation: 33
I am trying to pass an empty vector of structures to a function which will read from a file and it will return the number of records read -- it will be an integer.
I initialize the vector of structures in main and when I attempt to pass it to the function as I would regularly do it:
int read_records(vector<player> player_info)
It gives me a "player is undefined" error. I have found a way to go around it as you will see in my code below but logic leads me to believe that there should be a way to pass the empty vector without having to fill in the first subscript.
The code is below. Please note that the read function is not yet complete as I am still wondering about the vector of structs.
#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;
//function prototypes
int read_records(struct player* player_info);
/*
* Define a struct called player that will consist
* of the variables that are needed to read in each
* record for the players. 2 strings for the first
* and last names and 1 integer to hold the statistics
*/
struct player
{
string first;
string last;
int stats;
};
int main(void)
{
int sort_by, records_read;
vector<player> player_info(1);
player * point = &player_info[0];
cout << "Welcome to Baseball player statistics program!" << endl;
cout << "How should the information be sorted?" << endl;
cout << "Enter 1 for First Name" << endl;
cout << "Enter 2 for Last Name" << endl;
cout << "Enter 3 for Points" << endl;
cout << "Enter your selection: ";
cin >> sort_by;
//read the records into the array
records_read = read_records(point);
system("Pause");
return 0;
}
int read_records(struct player* player_info)
{
//declare the inputstream
ifstream inputfile;
//open the file
inputfile.open("points.txt");
//handle problem if the file fails to open for reading
if (inputfile.fail())
{
cout << "The player file has failed to open!" << endl;
exit(EXIT_FAILURE);
}
else
{
cout << "The player file has been read successfully!" << endl;
}
return 5;
}
Upvotes: 2
Views: 1650
Reputation: 3260
Why don't you put struct player
definition before int read_records(vector<player> player_info)
.
Upvotes: 0
Reputation: 385204
Define the type player
before you attempt to declare functions that need to know about that type.
struct player
{
string first;
string last;
int stats;
};
int read_records(vector<player> player_info);
Your workaround was successful because naming player
in struct player*
acts as a [forward] declaration, in a way that naming it in vector<player>
does not. (The whys and wherefores of this are too broad for this answer and are covered elsewhere on SO and in your C++ book.)
As an aside, I doubt you want to take that vector by value.
Upvotes: 5