使用光标操作打印垂直直方图c++ [ncurses][解决了无ncurses]

Printing a vertical histogram with cursor manipulation C++[ncurses][Solved w/o ncurses]

本文关键字:ncurses 解决 c++ 直方图 光标 操作 打印 垂直      更新时间:2023-10-16

我以前问过这样的问题,但它有点误导,因为我没有包括打印顺序。因为我知道整个概念都改变了,我想再问一遍会更合适。

 #include <iostream>
    using namespace std;
    int main()
    {
        int a, b, c, i;
        cin >> a >> b >>  c;
        for ( i = 0;  i < a; i++)
            cout << "*" << endl;
        for ( i = 0; i < b; i++)
            cout << "*" << endl;
        for ( i = 0; i < c; i++)
            cout << "*" << endl;
    }

我知道输出和

一样
for ( i = 0; i < a + b + c; i++ ){
cout << "*" << endl;
}

那么对于2 3 1,我得到:

*

*

*

*

*

*

我要的是:

     *
*    * 
*    *    *   //Horizontal distance between 2 shapes don't matter.

必须完全按照这个顺序来做。而且,每一列的打印必须用一个单独的功能来完成。

第一个循环:

*
*

第二个循环:

    *
*   *
*   *
去年循环:

    *
*   *
*   *   *

*EDIT:*显然还有一个不使用游标操作的解决方案。我的老师建议我应该先将字符存储在一个char指针中,然后逐行打印该char指针内存。

下面是一个curses程序来做这件事

#include <iostream>
#include <curses.h>
using namespace std;
int main(int argc, char** argv)
{
  int a,b,c,i;
  cin >> a >> b >> c;
  initscr(); // initialise curses
  int rows, cols;
  getmaxyx(stdscr, rows, cols);  // get screen size

  for (i=0; i<a; i++) {
    mvprintw(rows - 1 - i, 0, "*"); // plot at bottom column 0
  }
  for (i=0; i<b; i++) {
    mvprintw(rows - 1 - i, 1, "*"); // plot at bottom column 1
  }
  for (i=0; i<c; i++) {
    mvprintw(rows - 1 - i, 2, "*"); // plot at bottom column 2
  }
  refresh();  // update screen
  getch(); // exit when key is pressed
  endwin(); // exit curses
  return 0;
}

你不能按你想要的方式来做。您需要一次打印一条水平线,因为您不能垂直输出到控制台。

所以首先你需要找出你总共需要多少行,totalLines,这是a, bc的最大值。然后,您应该遍历每一行。

在行迭代中,您需要在正确的位置打印出正确数量的* s。是否需要为a画一个点的条件是a >= totalLines - line(其中line是当前的线,从0开始为第一条线)。与bc类似,因此您需要3条if语句,其中每个语句打印空格或*