c++ - 结构数组和文件 I/O

标签 c++

//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/

相关文章:

c++ - 将十进制转换为 ASCII

c++ - &= 必须始终被解释为运算符吗?

c++ - 为什么memcpy()和其他类似函数使用汇编程序?

python - 在c中嵌入Python,然后在c++程序中运行它不起作用

c++ - 将 QStringList 元素拆分为更多元素

c++ - 为什么我无法进行此转换?

c++ - Qt:带有文本浏览器的模型/ View 概念

C++生态系统模拟器(继承)

C++:使用 boost::regex 将管道分隔的字符串与通配符匹配

c++ - 在另一个项目 visual studio 中使用一个项目中的目标文件