【问题标题】:Can't pass filestream as function parameter?不能将文件流作为函数参数传递?
【发布时间】:2017-03-14 04:13:15
【问题描述】:

这是我的作业代码。每当我尝试编译时,由于“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;
    }
}

【问题讨论】:

  • 请包含实际的错误代码。

标签: c++ string file inputstream filestream


【解决方案1】:

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

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

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

等等……

【讨论】:

  • 非常感谢,我已经编译好了。现在唯一的问题是输出文件除了一个空行之外什么都没有?我知道正确填充数组然后将其放入输出流吗?
  • 您的代码中有错误。您调用read() 两次,它会一直读取到文件末尾。然后代码再次调用read(),并将其返回值传递给print()。您认为第二次调用read() 会读取多少条记录?
  • 哦,呃,忘了我的尺寸常数。我的输出文件现在正在返回内容,但不是名称和平均成绩,而是胡言乱语。输出应该是“Coop, Jason = 27.31”,但它只是随机数字和字母的混合。
【解决方案2】:

Sam Varshavchik 的回答是正确的,但他没有提到为什么流对象不允许你复制它们。

这里的问题是流对象拥有一个缓冲区,而缓冲区不能安全地复制。

举个例子,假设您有数据通过网络套接字传入,并且前面有一个缓冲区,并且您复制了这个缓冲的读取器。如果您从副本中读取,它将读取一些不确定数量的数据并将其放入缓冲区。该数据现在已从网络套接字中消失,仅存在于缓冲区中。现在假设您从副本中读取。然后你会得到一些不确定数量的数据,这些数据是在你在原始数据中读取的数据之后出现的。以这种方式来回移动,您会得到两个“流”,其中另一个读取器正在读取数据。

【讨论】:

    猜你喜欢
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 2021-04-13
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多