//i have two errors in my code
#include <iostream>
#include<iomanip>
#include<fstream>
using namespace std;
struct PLAYER
{
string first_name;
string last_name;
};
void showFile(fstream&, PLAYER&); // line 13
int main()
{
const int MAX=21;
PLAYER array[MAX];
ifstream inputFile;
inputFile.open("PlayerNames.txt",ios::in);
if(inputFile)
{
showFile(inputFile, array); // line 22
}else
cout<<"\n\nError opening file";
inputFile.close();
return 0;
}
void showFile(fstream &file, PLAYER &array )
{
int index=0;
int p_num=1;
string lname, fname;
file>>lname>>fname;
while(!file.eof())
{
// array[index].last_name=
cout<<lname<<" "<<fname;
//array[index].first_name=fname;
//array[index].player_number=p_num;
index++;
p_num++;
file>>lname>>fname;
}
// cout<<"\n"<<index;
//cout<<lname<<" "<<fname;
}
这个程序终于工作了,直到我把它放在函数中。 我在这个程序中有两个错误 第22行错误:引用类型std :: fstream的初始化无效 第13行错误:传递void showFile的参数1(std :: fstream&amp;,PLAYER&amp;)
答案 0 :(得分:1)
第13行的函数声明显示您传递的是1 PLAYER
个对象,而不是数组。如果你想继续使用数组,请在StackOverflow中搜索&#34; [C ++]传递数组函数&#34;。
我强烈建议使用std::vector
,因为它在传递给函数时具有更简单的语法。
答案 1 :(得分:1)
ifstream
无法转换为fstream
,只能转换为istream
。
在the documentation中,您可以看到basic_ifstream
来自basic_istream
,而不是basic_fstream
。
使你的功能:
void showFile(istream&, PLAYER&);
这在很多方面实际上更好。一个是正确的(c:但它也意味着你可以使用任何输入流而不仅仅是文件流来测试它。它更松散地耦合并编程到更抽象的界面。