//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(std::fstream&, PLAYER&) 的参数 1
最佳答案
ifstream
无法转换为 fstream
,只能转换为 istream
。
在the documentation你可以看到 basic_ifstream
派生自 basic_istream
,而不是 basic_fstream
。
让你的功能:
void showFile(istream&, PLAYER&);
这实际上在很多方面都更好。一方面它是正确的 (c: 但它也意味着您可以使用任何输入流而不只是文件流来测试它。它更松散地耦合并且编程到更抽象的接口(interface)。
关于c++ - 结构数组和文件 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16510721/