2013-05-19 61 views
5

所以我有一個函數(或者說,稍後我將把它變成一個函數)在控制檯窗口中做一個隨機的%進度;像這樣:製作控制檯進度條? (Windows)

#include <iostream> 
#include <time.h> 
#include <cmath> 
#include <windows.h> 

using namespace std; 

int main() 
{ 
    srand(time(0)); 
    int x = 0; 

    for(int i = 0; i<100; i++){ 
     int r = rand() % 1000; 
     x++; 
     cout << "\r" << x << "% completed." << flush; 
     if(i < 43){ 
      Sleep(r/6); 
     }else if(i > 43 && i < 74){ 
      Sleep(r/8); 
     }else if(i < 98){ 
      Sleep(r/5); 
     }else if(i > 97 && i != 99){ 
      Sleep(2000); 
     } 
    } 

    cout << endl << endl << "Operation completed successfully.\n" << flush; 
    return 0; 
} 

的事情是,我所要的輸出是這樣的:

1% completed 

| 

(後...)

25% completed 

||||||||||||||||||||||||| 

我怎麼能這樣做?

在此先感謝!

+0

超過兩行,你不能。在一行上如何「X%完成|||||」 ...「XX%已完成|||||||||||」 ...? –

回答

13

打印字符'\r'很有用。它將光標放在行的開頭。

既然你不能訪問前行了,你可以有這樣的事情:

25% completed: |||||||||||||||||| 

後每次迭代:

int X; 

... 

std::cout << "\r" << percent << "% completed: "; 

std::cout << std::string(X, '|'); 

std::cout.flush(); 

此外,您還可以使用:Portable text based console manipulator

+0

謝謝,它的作品!但是,沒有辦法通過兩行來完成嗎? – Adam

+0

噢,但由於某種原因,它打破了%計數器。在66%之後,當它到達控制檯邊緣時,它將不斷打印出在新行上完成的百分比 – Adam

+0

儘量避免超出行數的'|'長度。 – deepmax

0

我認爲這看起來更好:

#include <iostream> 
#include <iomanip> 
#include <time.h> 
#include <cmath> 
#include <windows.h> 
#include <string> 

using namespace std; 
string printProg(int); 

int main() 
{ 
    srand(time(0)); 
    int x = 0; 
    cout << "Working ..." << endl; 
    for(int i = 0; i<100; i++){ 
     int r = rand() % 1000; 
     x++; 
     cout << "\r" << setw(-20) << printProg(x) << " " << x << "% completed." << flush; 
     if(i < 43){ 
      Sleep(r/6); 
     }else if(i > 43 && i < 74){ 
      Sleep(r/8); 
     }else if(i < 98){ 
      Sleep(r/5); 
     }else if(i > 97 && i != 99){ 
      Sleep(1000); 
     } 
    } 

    cout << endl << endl << "Operation completed successfully.\n" << flush; 
    return 0; 
} 

string printProg(int x){ 
    string s; 
    s="["; 
    for (int i=1;i<=(100/2);i++){ 
     if (i<=(x/2) || x==100) 
      s+="="; 
     else if (i==(x/2)) 
      s+=">"; 
     else 
      s+=" "; 
    } 

    s+="]"; 
    return s; 
}