2011-04-21 38 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。