Home > Software engineering >  C | Input the following string inside a rectangle
C | Input the following string inside a rectangle

Time:09-02

I would like to input the following code inside a rectangle, so that the output would be the rectangle with my printed text.

Here is my code:

#include <iostream>
 
using namespace std;
 
int main() {

    cout <<" * Programming Assignment *" << endl;
    cout <<" * Data Structures *" << endl;
    cout <<" * Author: Hello World  * " << endl;
    cout <<" * Due Date: September, 7th * " << endl;

    return 0;
}

Here is the text OUTPUT I want to be in the Rectangle:

* Programming Assignment *
* Data Structures *
* Author: Hello World *
* Due Date: September, 7th *

Do you have any tips on how to do this, I've already checked the tutorial bellow, but that did not help clarify my answer:

Print out a text in the middle of a rectangle

CodePudding user response:

You can use #include <iomanip> header, which includes convenient objects which you can pass into cout, to manipulate the output: std::setw(width) to specify that the next thing you print (text in our case) will have to be padded to have exactly width characters, std::setfill(' ') to specify with which character you pad the text, and std::left to tell to align the text to the left, and pad with spaces to the right.

#include <iostream>
#include <iomanip> 
using namespace std;

void print_box_border(int width, bool is_top) {
    if (is_top) { cout << "┌"; }
    else { cout << "└"; }
    for (int i = 0; i < width;   i) {
        cout << "─";
    }
    if (is_top) { cout << "┐\n"; }
    else { cout << "┘\n"; }
    
}

void print_box_row(int width, const char * text) {
    cout << "│" << std::setfill(' ') << std::setw(width) << std::left << text <<  "│\n";
}

int main()
{
    int box_width = 50;
    print_box_border(box_width, /*is_top*/ true);
    print_box_row(box_width, " * Programming Assignment *");
    print_box_row(box_width, " * Data Structures *");
    print_box_row(box_width, " * Author: Hello World  * ");
    print_box_row(box_width, " * Due Date: September, 7th * ");
    print_box_border(box_width, /*is_top*/ false);
    return 0;
}

Output I get:

┌──────────────────────────────────────────────────┐
│ * Programming Assignment *                       │
│ * Data Structures *                              │
│ * Author: Hello World  *                         │
│ * Due Date: September, 7th *                     │
└──────────────────────────────────────────────────┘
  •  Tags:  
  • c
  • Related