简体   繁体   中英

skipping characters with printf

I'm trying to write a program which would write on the console at a very specific position in the screen. Say for example from column 20 to column 39. After each write, the line is "reset" thanks to the \\r parameter. This ensures that the line remains static and only the specific fields are updated.

Problem is, i can instruct printf to write from column 0 to 19 without erasing the rest of the line, but it seems i'm not able to instruct printf to write from column 20 onwards without erasing in the process columns 0 to 19.

Is there a (standard) way to do this ? using something else than printf is possible.

[Edit] I've read there is a gotoxy() function in C which is available for windows apparently, and can be emulated in Linux using ncurses. Is there any problem with this function ?

AFAIK没有标准的方法来执行此操作,因为没有控制台行为标准化(例如Windows的控制台不像Linux的行为)

According to ANSI documentation , you can use "\\033[1;20H" to position the cursor.

It will move the cursor to the needed position. The values 1 and 20 are the row and the column, just change it to position correctly your print.

Or you can try with only "\\033[20C" to move your cursor to column 20.

You can try printing as many backspaces (and spaces to clear old text) as needed to position the cursor.

No guarantee it works for you ... if it does: no guarantee it works on the other computer :)

#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;
}

It works for me, on both Linux and Windows computers

I have had the same trouble before. I used gotoxy() when I coded in TurboC++.

Check this out. Looks good.

http://www.daniweb.com/software-development/c/code/216326#

为什么你不只是sprintf(myStr,....并在内存中构建行然后一次输出它?你可以保留你想要的字段来自上一次更新。

Marc Rochkind wrote a realy good book which is the leading reference on the subject! Advanced C Programming for Displays: Character Displays, Windows, and Keyboards for the Unix and Ms-DOS Operating Systems

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM