我有一个 C++ 程序,我用它在文件中插入信息。我有第二个(这个)程序来获取数据。我的目标是获取所有数据并将其作为 Student 类型的数组返回。在 GetFromFile 方法中,我正在获取信息并且可以打印它,但是我如何返回它并在主函数中像这样使用它:
int size;
Student *students = getFromFile( "D:\\test.txt", size );
cout << students[0].name;
我得到的错误是
[Warning] address of local variable `students' returned
这是我的代码:
struct Student
{
string name;
char egn[11];
short grade;
double avg_grades;
int excused, unexcused;
};
Student* getFromFile(string filename, int &length)
{
fstream file;
file.open(filename.c_str(), ios::in);
file >> length;
Student students[length];
for ( int i = 0; i < length; i++ )
{
file >> students[i].name >> students[i].egn >> students[i].grade >> students[i].avg_grades >> students[i].excused >> students[i].unexcused;
}
file.close();
return students;
}
int main()
{
int size;
Student *students = getFromFile( "D:\\test.txt", size );
cout << students[0].name;