如何用ncurses绘制直方图?

时间:2013-01-27 13:33:35

标签: c histogram ncurses

我有一个代码从输入读取,计算字母并绘制直方图作为ASCII艺术。我想用ncurses做同样的事情。怎么做?

#include <stdio.h>
int main(void) {
  int c, i, j;
  int chars[256];
  // a counter for every character in the ASCII set
  for (i = 0; i < 256; ++i) {
    chars[i] = 0;
  }
  // check each input and increment the relative element
  while ((c = getchar()) != '0') {
    ++chars[c];
  }
  // print only those characters that were received
  for (i = 0; i < 256; ++i) {
    // go through every element in chars
    if (chars[i] > 0) {
      // print headers
      if (i == ' ')
        printf(" Space: ");
      else if (i == '\n')
        printf("    \\n: ");
      else if (i == '\t')
        printf("   tab: ");
      else
        printf("%6c: ", i);
      for (j = 0; j < chars[i]; ++j)
        // print a # for every tally of each element; chars[i] is the tally
        putchar('#');
        // and we need to go through each from 0 to the final tally of that element
      printf("\n");
    }
  }
}

1 个答案:

答案 0 :(得分:1)

使用Curses开发工具包中的CDK Histogram。这很容易; here是演示用法的示例代码(取自Debian libcdk包)。