通过函数传递ifstream文件时出错

时间:2014-08-11 18:02:28

标签: c++ file function include ifstream

这是我的代码:

#include <string>
#include <iomanip>
#include <fstream>
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;

// include .h file that holds function ot write header
#include "WriteE3RptHdr.h"

// declare global constant
const int NUM_QTS = 15;

// declare struct to hold info on student and answers
struct StudRpt {
    char answers[NUM_QTS];
    string firstName;
    string lastName;
    char answerKey[NUM_QTS];
    string testKey;
    string testData;
};

StudRpt Data;

// function prototypes
StudRpt StoreAnswerKey(StudRpt Data, ifstream inFile);
StudRpt StoreStudData(StudRpt Data, ifstream inFile);
void WriteRpt(StudRpt Data, ofstream& outFile);

int main()
{
    int correct;
    int inforrect;
    int score;
    // delcare and open file streams
    ifstream inFile;
    ofstream outFile;
    inFile.open("in.data");
    outFile.open("out.data");

    // call function included from .h file
    WriteRptHdr(outFile);

    StoreAnswerKey(Data, inFile);

    // priming read
    StoreStudData(Data, inFile);

    while (inFile) {
        StoreStudData(Data, inFile);
        WriteRpt(Data, outFile);
    }
    inFile.close();
    outFile.close();
}
//----------------------------------------------------
StudRpt StoreAnswerKey(StudRpt Data, ifstream inFile) {
    int i;
    for (i = 0; i < NUM_QTS; i++) {
        inFile >> Data.answers[i];
    }

    return Data;
}

函数WriteRptHdr包含在.h文件中。它通过一个函数传递 - 我已经测试过了,它运行得很好。但ifstream inFile不起作用(该程序是为了读取答案键,并将它们与学生给出的答案进行比较。我无法通过传递的ifstream读取答案键)

我正在使用Pico。这就是我得到的错误:

In function 'int main()':
Tester.cxx:48: note: synthesized method 'std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(const std::basic_ifstream<char, std::char_traits<char> >&)' first required here
Tester.cxx:48: error: initializing argument 2 of 'StudRpt StoreAnswerKey(StudRpt, std::ifstream)'

1 个答案:

答案 0 :(得分:2)

您无法按值传递流,因为流不可复制。

相反,传递对流的引用(以及您的StudRpt):

StudRpt StoreAnswerKey(StudRpt& Data, ifstream& inFile);
StudRpt StoreStudData(StudRpt& Data, ifstream& inFile);