的左边 。必须有class / struct / union c ++错误

时间:2014-09-20 19:58:59

标签: c++

我试图通过指针引用传递给函数来打开输入和输出文件,但每次我尝试编译程序时都会出现错误:“.open'的左边必须有一个类/结构/联合有人可以帮助看看这段代码有什么问题吗?

#include <fstream>
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cctype>

using namespace std;

void PrepareFiles(ifstream* fin, ofstream* fout);

int main(){
    ifstream fin;
    ofstream fout;

    PrepareFiles(&fin, &fout);

    fin.close();
    fout.close();
    return EXIT_SUCCESS;
}

void PrepareFiles(ifstream* fin, ofstream* fout)
{
    char inputFilename[MAX_LENGTH_FN + 1],
         outputFilename[MAX_LENGTH_FN + 1];

    cout << "Input filename (up to " << MAX_LENGTH_FN << " characters): ";
    cin.get(inputFilename, MAX_LENGTH_FN + 1, '\n');
    cin.ignore(999, '\n');
    cout << "Output filename (up to " << MAX_LENGTH_FN << " characters): ";
    cin.get(outputFilename, MAX_LENGTH_FN + 1, '\n');
    cin.ignore(999, '\n');

    *fin.open(inputFilename, ios::in);
    if (*fin.fail())
    {
        cerr << "Error opening input file " << inputFilename;
        exit(EXIT_FAILURE);
    }

    *fout.open(outputFilename, ios::out);
    if (*fout.fail())
    {
        cerr << "Error opening output file " << outputFilename;
        exit(EXIT_FAILURE);
    }
}

1 个答案:

答案 0 :(得分:1)

.的优先级高于*,因此*fin.open(inputFilename, ios::in);(和其他)被解释为*(fin.open(inputFilename, ios::in));,这是不正确的,因为fin是指针。

使用括号或更好,->。或者甚至更好,通过引用传递参数,我没有看到需要通过指针。