Jawad Adil
Jawad Adil

Reputation: 67

How to create an ASCII-Art bar chart in C++?

I have a question regarding C++ while loop. I want to draw an ASCII-Art bar chart such as this:

      *
*     *
* *   *
* * * *
* * * *
* * * *

For this I need to fill the output from below. I have the following code which draws a single bar from "top to bottom", but I need to somehow leave the space above the bar so that the other bars fit nicely:

#include<iostream>

using namespace std;

int main()
{
    int a,n;
    cout << "Enter a value in range 5-20 \n";
    cin >> a;
    while (n<a) {
        cout<<"* \n";
        n=n+1;
    }
 }

As mentioned, this code doesn’t leave space above the bar, so it won’t align with other bars. How can I solve this?

Upvotes: 2

Views: 1554

Answers (2)

kubre
kubre

Reputation: 166

I can say try to find how many no of rows in your full screen mode you have Follow these steps:

  1. Print the screen from top to bottom with stars.
  2. Then count those stars to get idea how many lines(row) on your screen are.

ex.

*
*
*
*

This means you have 4 rows.

  1. Then take input from user.
  2. Now subtract user input from no of rows. i.e. 4 so if user give you 2 as input then fill screen with two spaces then 2 stars.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490018

Standard C++ doesn't provide any way to do that.

Given the requirement you've shown in the comments (you want to create a bar graph out of characters), what you probably want to do is start by creating a 2D array of characters the size of the output you're going to create.

  • Start by filling it with space characters.
  • Then fill in asterisks where needed to create your chart. Since it's just an array, you can access elements in any order you prefer.
  • Then write it out to the screen from left to right, top to bottom.

Upvotes: 1

Related Questions