Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that asks the user for a positive integer no greater than 15. Th

ID: 3696277 • Letter: W

Question

Write a program that asks the user for a positive integer no greater than 15. The program should then store a square on a file using the character ‘X’. The number entered by the user will be the length of each side of the square. For example, if the user enters 5, the program store the following pattern in a file named “pattern.dat”

XXXXX

XXXXX

XXXXX

XXXXX

XXXXX

The program should then read the stored pattern from the file you just created and display the pattern on the screen.

This is what I have so far, it runs but it isnt printing the x's. I dont know where I went wrong.

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

int main()

{

int num,i=0;

fstream myfile("pattern.dat");

myfile.open("pattern.dat", ios::out | ios::in);

string item;

cout << "Enter a number equal to or less than 15: " << endl;

cin >> num;

for(int i=0; i<num; i++)

{

for(int j=0; j<num; j++)

{

myfile << "x";

}

myfile << " ";

}

while(myfile >> item)

cout << item << endl;

myfile.close();

return 0;

}

Explanation / Answer

#include <iostream>

#include <fstream>

#include <string>

using namespace std;

int main()

{

        int num,i=0;

        ofstream myfile;
        myfile.open("pattern.dat");

        cout << "Enter a number equal to or less than 15: " << endl;

        cin >> num;

        for(int i=0; i<num; i++)

        {

        for(int j=0; j<num; j++)

        {

        myfile << "x";

        }

        myfile << " ";
        }
        myfile.close();
      
        char data[100];
        ifstream infile;
        infile.open("pattern.dat");
        while(infile>>data)
        {
            cout<<data<<endl;
        }
         myfile.close();

        return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote