Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何使用iofstream将函数的输出写入文件?_C++ - Fatal编程技术网

C++ 如何使用iofstream将函数的输出写入文件?

C++ 如何使用iofstream将函数的输出写入文件?,c++,C++,我正在完成一项任务: 提示用户输入不少于1582的年份 生成一个文件cal.dat,其中包含我编写的代码生成的日历 我写了一段代码,它接受输入,计算是否是闰年,然后用cout返回当年的日历 当我尝试将日历输出到文件Xcode时,在编译时出现以下错误: Invalid operands to binary expression ('ofstream' (aka 'basic_ofstream<char>') and 'void') 代码的一部分如下所示: #include <i

我正在完成一项任务:

提示用户输入不少于1582的年份

生成一个文件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;
}

编写日历时,需要向PrintMonth添加一个流参数,并使用该参数而不是cout。PrintMonth返回void。。。。当你调用该函数时,你认为你在向你的ofstream写什么?投票重新打开,因为提问者提供了足够的信息,回答者可以给出一个好的答案。当我简单地输入PrintMonthyear,leap时,日历打印得很好,就像我使用cout一样。void函数是从以前的赋值中继承下来的,所以如果我想让它返回它打印出来的东西,我应该把它转换成int函数吗?对于int函数,一次只能返回一个int,但不能返回它打印出来的一系列东西。我建议更改PrintMonth,使其写入日历,而不是将内容打印到控制台。因此,复制PrintMonth的代码并相应地修改它。我认为更好的建议是将std::ostream&类型的另一个参数添加到PrintMonth,并将其用作函数内部要打印的流,而不是打印到全局变量。@Nenjamin Lindley:对,修改了答案。