2013-05-19 60 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; 
}