ofstream outFile

I can't figure how to write the output to the file Pattern.txt
Last edited on
You need to store what you're doing in displayStars in a variable. Make it return a string, and from that you can output the string into the text file.
Another approach. You could replace the cout in lines 26 and 27 with outputFile. Call function displayStars() after the file has been opened at line 15.

The problem then is that function displayStars() would have no idea what outputFile is, so the program would not compile. One solution to that would be to move the declaration of outputFile out of main(), place it in the global scope at the top of the code. Or to avoid the use of a global variable, instead pass by reference the outputFile as a third parameter to the function which uses it.
I updated it to return a string, I still don't know whats wrong.

Last edited on
closed account (E0p9LyTq)
You are still sending your output to the console instead of "building" a string, and your function's return is still void.
How do i build a string?
closed account (E0p9LyTq)
You might want to learn about the C++ std::basic_string library <string> and the string stream library <sstream>.
For the sake of completeness, here's my original suggestion in full:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <fstream>

void displayStars(int, int);
std::ofstream outputFile; // declaration moved here

int main()
{
    outputFile.open("Pattern.txt");

    displayStars(2,1);
    displayStars(4,1);
    displayStars(8,1);
    displayStars(16,1);

    return 0;
}

void displayStars(int cols, int rows)
{
    for (int down = 0; down < rows; down++)
    {
        for (int across = 0; across < cols; across++)
            outputFile << '*'; // cout replaced by outputFile 
        outputFile << '\n';    // ---- ditto ----
    }
}
Topic archived. No new replies allowed.