我正在尝试将一个空的结构向量传递给一个函数,该函数将从一个文件中读取,它将返回读取的记录数 - 它将是一个整数。
我在main中初始化结构的向量,当我尝试将它传递给函数时,我会经常这样做:
int read_records(vector<player> player_info)
它给了我一个“玩家未定义”的错误。我已经找到了解决它的方法,你将在下面的代码中看到,但逻辑让我相信应该有一种方法来传递空向量而不必填写第一个下标。
代码如下。请注意,读取功能尚未完成,因为我仍然想知道结构的向量。
#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;
}
答案 0 :(得分:5)
在之前定义类型player
,以尝试声明需要了解该类型的函数。
struct player
{
string first;
string last;
int stats;
};
int read_records(vector<player> player_info);
您的解决方法之所以成功,是因为在player
中命名struct player*
充当[转发]声明,而在vector<player>
中命名它不会。 (这个问题的原因和原因对于这个答案而言过于宽泛,并且在SO和C ++书籍的其他地方都有涉及。)
顺便说一句,我怀疑你想按价值取得那个载体。
答案 1 :(得分:0)
为什么不在struct player
之前添加int read_records(vector<player> player_info)
定义。