c++ - 无法将文件流作为函数参数传递?

标签 c++ string file inputstream filestream

这是我的作业代码。每当我尝试编译时,由于“ios_base.h”中的某些内容,我的读取函数都会出错,我不确定该怎么做和/或我的代码是否执行了获取文件并将其元素移动到单独的文件的预期功能名称和平均值相邻的文件。

#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>

using namespace std;

struct Student
{
    string fname;
    string lname;
    double average;
};

int read(ifstream, Student s[]);

void print(ofstream fout, Student s[], int amount);


int main()
{
    const int size = 10;
    ifstream fin;
    ofstream fout;
    string inputFile;
    string outputFile;
    Student s[size];

    cout << "Enter input filename: ";
    cin >> inputFile;
    cout << "Enter output filename: ";
    cin >> outputFile;
    cout << endl;

    fin.open(inputFile.c_str());
    fout.open(outputFile.c_str());

    read(fin , s);
    print(fout, s, read(fin, s));

}

int read(ifstream fin, Student s[])
{
    string line;
    string firstName;
    string lastName;
    double score;
    double total;
    int i=0;
    int totalStudents=0;
    Student stu;

    while(getline(fin, line)){
        istringstream sin;
        sin.str(line);

        while(sin >> firstName >> lastName){
            stu.fname = firstName;
            stu.lname = lastName;

            while(sin >> score){
            total *= score;
            i++;
            }
            stu.average = (total/i);
        }
        s[totalStudents]=stu;
        totalStudents++;
    }
    return totalStudents;
}

void print(ofstream fout, Student s[], int amount)
{
    ostringstream sout;
    for(int i = 0; i<amount; i++)
    {
        sout << left << setw(20) << s[i].lname << ", " << s[i].fname;
        fout << sout << setprecision(2) << fixed << "= " << s[i].average;
    }
}

最佳答案

流对象不可复制。他们的复制构造函数被删除。它们必须通过引用传递,而不是通过值传递:

int read(ifstream &, Student s[]);

void print(ofstream &fout, Student s[], int amount);

等...

关于c++ - 无法将文件流作为函数参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40353017/

相关文章:

python - 在 Python 中打开文件以查看各个位

c++ - 带有内存大小定义的 header

C++ 代码在 CodeBlocks 中构建,但不在 Visual Studio 2015 中构建

java - 连接字符串对象列表的最佳方法?

string - 如何用内部@""@封装脚本,用外部@""@

java - 在 String Java 中搜索并替换 SSN 和/或信用卡

c++ - 如何使用 qteSTLib 测试完整的 Qt5 GUI?

c++ - Linux 上写入共享内存时出现周期性延迟峰值

c - 只获取c/Ubuntu中某个目录下的文件

javascript - angularjs捕获音频并上传文件