2017-02-02 76 views
0

我处理作业是:如何使用iofstream将函数的输出写入文件?

  1. 提示用户一年投入不低于1582

  2. 生成一个文件(cal.dat)包含的代码我公司生产的日历写。

我写了需要输入,计算它是否是闰年,然后还给当年与cout日历的代码。

当我尝试输出日历文件的Xcode给了我这个错误在编译:

Invalid operands to binary expression ('ofstream' (aka 'basic_ofstream<char>') and 'void') 

代码的一部分是低于:

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

using namespace std; 

void PrintMonth(int year, bool leap); 
ofstream calendar("cal.dat"); 

int main() 
{ 
    // Setting up the parameters for the PrintMonth function 
    int year=0; 
    bool leap=false; 

    // Input for the year 
    cout << "Enter a 4 digit year: "; 
    cin >> year; 

    // Loop for an incorrect entry 
    while (year<1582) 
     { 
     cout << "Year too low, please re-enter: "; 
     cin >> year; 
     } 

    // Calculate if the input year is a leap year or not 
    if ((year%4==0 && year%100!=0) || year%400==0) 
     leap=true; 

    // Output the year and the calendar for the year requested 
    calendar << setw(15) << year << endl << endl; 
    calendar << PrintMonth(year, leap); 

    return 0; 
} 
+0

您需要将一个流参数添加到'PrintMonth'并使用该参数代替'cout'。 – molbdnilo

+0

'PrintMonth'返回'void' ....当你调用这个函数时,你认为你正在给你的'ofstream'写什么? – CoryKramer

+0

投票重新打开,因为提问者已经给答案者足够的信息以给出一个很好的答案。 –

回答

1

你写calendar << PrintMonth(year, leap),这将意味着您将PrintMonth的返回值传递给calendar。 但是,根据签名void PrintMonth(int year, bool leap),此函数不会返回可打印的值。 您的意思是PrintMonth(year,leap);而不是calendar << PrintMonth(year,leap)

所以,你可以复制你的PrintMonth功能全,签名更改为void PrintMonth(int year, bool leap, std::ostream& out),调整其执行写信给out而不是cout,并呼吁PrintMonth(year,leap, calendar);,而不是写calendar << PrintMonth(year,leap)

+0

当我简单地把PrintMonth(年,闰年),日历打印出来好像我用cout。 void函数是从前一个赋值中继承下来的,所以如果我希望它返回它打印出来的东西,我应该把它变成一个int函数吗? –

+0

用'int'函数,你一次只能返回一个int,但不能是一系列“打印出来的东西”。我建议改变'PrintMonth',而不是打印出一些东西来控制 - 它写入'日历'。因此,复制'PrintMonth'的代码并相应地更改它。 –

+0

我认为一个更好的建议是将另一个参数(类型'std :: ostream&')添加到'PrintMonth',并将其用作打印到函数内部的流,而不是打印到全局变量。 –

相关问题