c - 使用 printf 跳过字符

标签 c console

我正在尝试编写一个程序,该程序将在屏幕上非常特定的位置写入控制台。例如从第 20 列到第 39 列。 每次写入后,由于 \r 参数,该行被“重置”。这确保该行保持静态并且仅更新特定字段。

问题是,我可以指示 printf 从第 0 列写入到第 19 列而不删除该行的其余部分,但似乎我无法指示 printf 从第 20 列开始写入而不删除进程中的第 0 列到第 19 列19.

是否有(标准)方法可以做到这一点? 使用 printf 以外的东西是可能的。

[编辑] 我读到 C 语言中有一个 gotoxy() 函数,它显然适用于 Windows,并且可以在 Linux 中使用 ncurses 进行模拟。这个功能有什么问题吗?

最佳答案

您可以尝试根据需要打印尽可能多的退格键(以及用于清除旧文本的空格)来定位光标。

不保证它对你有用......如果它适用:不保证它在另一台计算机上工作:)

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void) {
  int i, k;
  time_t oldtime = time(0);
  if (oldtime == (time_t)-1) {
    fprintf(stderr, "time function does not work on this machine\n");
    exit(EXIT_FAILURE);
  }
  while (time(0) == oldtime) /* void */;

  printf("fixed stuff: ");
  for (i = 1; i < 6; i++) {
    int val = pow(10, i) * i;
    printf("%d", val);
    fflush(stdout);
    oldtime = time(0);
    while (time(0) == oldtime) /* void */;
    if (i < 5) {
      for (k = 0; k < i + 1; k++) printf("\b \b"); // go back; erase; go back again
      fflush(stdout);
    } else {
      puts("");
    }
  }

  return 0;
}

它对我来说适用于 Linux 和 Windows 计算机

关于c - 使用 printf 跳过字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8052540/

相关文章:

c - 对C中的for循环感到困惑

c - 自由(): random error in recursive function

c - 在 C 中使用 fgets 跳过空行

c# Windows Service Console.Writeln 收藏

c# - 如何在控制台应用程序中获取光标的位置?

c++ - 从应用程序打开控制台

c - 为什么sctp_inet_listen的第一个参数是struct socket*而不是int

php - 将 LaTeX 渲染为图像

linux - Unix 命令 rmdir 什么时候适合使用?

bash - 一个晦涩难懂的问题:已记录的VT100“软包装”转义序列?