【问题标题】:Using gotoxy for printf with newlines将 gotoxy 用于带有换行符的 printf
【发布时间】:2021-03-30 13:26:07
【问题描述】:

我正在使用 ascii 创建带有输出的数字时钟,并且我制作了一个由五行组成的大量数字。我想使用 gotoxy 移动数字,但只有第一行移动,其余行忽略 y 坐标。

当我的 printf 有换行符时,如何使用 gotoxy 移动我的整个号码?

#include <stdio.h>
#include <time.h> 
#include <windows.h>
#include<conio.h>
void gotoxy(int col, int row);

void disp0();
int count=219;
int main()
{

gotoxy(10,10);disp0(); 

}

void gotoxy(int col, int row)
{
COORD coord;
coord.X = col; coord.Y = row;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void disp0(){
    printf("%c%c%c\n%c %c\n%c %c\n%c %c\n%c%c%c",count,count,count,count,count,count,count,count,count,count,count,count);//0

}

这是我得到的输出:

【问题讨论】:

  • Edit 并显示您的代码而不是描述它
  • 你在使用 Turbo C 吗?
  • 请不要发布您的代码图片,而是将您的代码发布为格式正确的文本
  • 我正在使用 devc++ 作为我的编译器
  • 当您打印\n 时,光标将位于屏幕最左侧的另一行,这是预期的行为。因此,不要天真地打印\n,而应该再次使用gotoxy 将光标定位在正确的位置。

标签: c printf newline


【解决方案1】:

您需要为每个单独的数字执行gotoxyprintf。不应该使用\n。如果你想变得花哨,你可以使用三角函数,就像这个非常草率的例子:

#include <stdio.h>
#include <windows.h>
#include <math.h>

void gotoxy(int x, int y)
{
  SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), 
                           (COORD){ .X=x, .Y=y });
}

int main() 
{
  const int center_x = 12;
  const int center_y = 12;
  const int radius = 6;
  double angle = 0;

  int clock [12] = {3, 2, 1, 12, 11, 10, 9, 8, 7, 6, 5, 4};

  for(int i=0; i<12; i++)
  {
    int x = round(radius * cos(angle));
    int y = round(radius * -sin(angle)); // - to shift y axis on console coord system
    angle += (2.0 * 3.1415) / 12.0; 

    // 2*x rough estimate to compensate for font height vs width:
    gotoxy(center_x + 2*x, center_y + y); 

    printf("%d", clock[i]);
  }
  gotoxy(1,center_y*2);
}

丑陋的输出:

            12
      11          1

  10                  2


9                       3


  8                   4

      7           5
            6

【讨论】:

  • 哦,等等,您实际上是在说数字时钟。这是......一个数字创建的模拟时钟......好吧,我希望你至少知道如何使用SetConsoleCursorPosition :)
猜你喜欢
  • 1970-01-01
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
相关资源
最近更新 更多