2011-04-21 89 views
2

什么,我想是做这样的事情:如何使光标转动

打印\然后|然后/然后_,它在一个循环下去。这里是我的代码:

#include <stdio.h> 

int main() 
{ 
    while(1) 
    { 
      printf("\\"); 
      printf("|"); 
      printf("/"); 
      printf("_"); 
    } 
    return 0; 
} 

我所面临的问题是,它打印它的顺序,我如何让它在打印用C或C++一些时间延迟相同的光标位置?

+1

请''包括',而不是'#包括',在编写C++时。 – 2011-04-21 12:53:59

回答

4

我不明白你的意思是How to make cursor rotate?但是,是你任何想要做这样的事情的机会:

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

#define mydelay 100 

void delay(int m) 
{ 
    clock_t wait = m+ clock(); 
    while (wait > clock()); 
} 


int main() 
{ 
    while(1) 
    { 
      printf("\\\b"); 
      delay(mydelay); 
      printf("|\b"); 
      delay(mydelay); 
      printf("/\b"); 
      delay(mydelay); 
      printf("_\b"); 
      delay(mydelay); 
    } 

    return 0; 
} 
+0

+1。尼斯。我在想它。 – Nawaz 2011-04-21 12:36:10

+0

是的,但它完全取决于环境是否有效。 'clock()'通常会测量进程的CPU时间,而不是时间。 – 2011-04-21 12:54:27

+0

@Nawaz ::谢谢。 – Sadique 2011-04-21 13:19:17

0

在C或C++中没有这样做的标准方法。

您可以使用第三方库,如ncurses或ANSI转义序列(如果在Unix操作系统上)。

2
#include <stdio.h> 

int main() 
{ 
    while(1) 
    { 
      printf("\\"); printf("%c", 8); // 8 is the backspace ASCII code. 
      printf("|"); printf("%c", 8); // %c is the printf format string for single character 
      printf("/"); printf("%c", 8); // assuming output to a terminal that understands 
      printf("_"); printf("%c", 8); // Backspace processing, this works. 
    } 
    return 0; 
} 

如果需要延迟,则调用添加到您自己的延迟函数忙等待,或来电睡觉,或者做一些其他处理。

1

您可以将回车添加到您的起点。

例如

printf("\r|"); 
sleep(1); 

或添加退格后printing.-

1

在C您可以用“\ B”或ASCII值8.使用打印退格字符每个打印之前。我想你会在两个打印语句之间需要一些延迟。

+0

如果你在Linux中,有这样的curses库。 – BiGYaN 2011-04-21 12:36:07

2
#include <stdio.h> 
#include <stdlib.h> /* for sleep() */ 

int main(void) 
{ 
    fprintf(stderr,"Here we are: "); 

    while(1) 
    { 
    fprintf(stderr,"\b\\"); 
    sleep(1); 
    fprintf(stderr,"\b|"); 
    sleep(1); 
    fprintf(stderr,"\b/"); 
    sleep(1); 
    fprintf(stderr,"\b-"); 
    sleep(1); 
    } 

    return 0; 
} 
2

可以印刷后再退格字符(\b),尽管这是否工作完全由地方正在显示你的程序的输出环境。

您还需要引入一个延迟,以便您可以真正看到更改(尽管这可能会自然发生,作为更广泛的算法的一部分)。

#include <cstdio> 
#include <cstdlib> 

int main() 
{ 
    while(1) { 
      printf("\\\b"); sleep(1); 
      printf("|\b"); sleep(1); 
      printf("/\b"); sleep(1); 
      printf("_\b"); sleep(1); 
    } 
    return 0; 
} 

您还可以查看the curses library以获取正确的基于文本的GUI fu。