C++结构,文件无法编译,矢量数组有问题



我不明白出了什么问题,但问题似乎出在矢量上,但在互联网上搜索后,我无法解决这个问题。

来自编译器的错误如下:

main.cpp:25:21: error: expected primary-expression before ‘&’ token
25 |     getdata(student &s,file);
|                     ^
main.cpp:26:23: error: expected primary-expression before ‘&’ token
26 |     printdata(student &s,file);
|                       ^
main.cpp: In function ‘void getdata(student&, std::fstream)’:
main.cpp:36:15: error: no match for ‘operator[]’ (operand types are ‘student’ and ‘int’)
36 |         cin>>s[i].name;
|               ^
main.cpp:38:15: error: no match for ‘operator[]’ (operand types are ‘student’ and ‘int’)
38 |         cin>>s[i].sno;
|               ^
main.cpp:40:15: error: no match for ‘operator[]’ (operand types are ‘student’ and ‘int’)
40 |         cin>>s[i].mark;
|               ^
main.cpp:44:34: error: no match for ‘operator[]’ (operand types are ‘student’ and ‘int’)
44 |         file<<"Student name: "<<s[i].name<<endl;
|                                  ^
main.cpp:45:36: error: no match for ‘operator[]’ (operand types are ‘student’ and ‘int’)
45 |         file<<"Student number: "<<s[i].snum<<endl;
|                                    ^
main.cpp:46:33: error: no match for ‘operator[]’ (operand types are ‘student’ and ‘int’)
46 |         file<<"term mark:   "<<s[i].mark<<endl;
|                                 ^
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
struct student
{
string name;
int snum;
double mark;
};
void getdata(student &s,fstream file);
void printdata(student &s,fstream file);
int main ()
{
fstream file;
int number;
vector <student> s(3);
cout<<"Enter number of students to account for: "<<endl;
cin>>number;

getdata(student &s,file);
printdata(student &s,file);
}
void getdata(student &s, fstream file)
{
file.open("Students.txt",ios::out);
for(int i=0; i<3; i++)
{
cout<<"Enter your name: "<<endl;
cin>>s[i].name;
cout<<"Enter your student number: "<<endl;
cin>>s[i].sno;
cout<<"Enter your term mark: "<<endl;
cin>>s[i].mark;
cout<<endl;

file<<"----------------------"<<endl;
file<<"Student name: "<<s[i].name<<endl;
file<<"Student number: "<<s[i].snum<<endl;
file<<"term mark:   "<<s[i].mark<<endl;
file<<"----------------------"<<endl;

}
file.close();
}
void printdata(student &s, fstream file)
{
file.open("Students.txt",ios::in);
string read;
while(getline(cin,read))
{
cout<<read<<endl;
}
file.close();
}

这些是无效的函数调用:

getdata(student &s,file);
printdata(student &s,file);

它们应该是:

getdata(s,file);
printdata(s,file);

这将导致其他错误,因为函数显然需要vector<student>,但只需要student

也不能按值传递fstream对象。它们必须是参考资料。

更改您的功能参数列表如下所示:

void getdata(vector<student> &s, fstream &file);
void printdata(vector<student> &s, fstream &file);

成员.sno也有一个拼写错误,你指的是.snum

解决所有这些问题,你的程序就会编译,然后你至少可以开始调试它,看看它是否有效。

最新更新