2011-09-21 31 views
1

我自學C++,我正在考慮一個簡單的程序來熟悉語法。接受int和print的C++程序*

int main(){ 
int num; 
cout << "Enter a positive number:"; 
cin >> num; 
printStar(num); 
} 

void printStar(int num){ 
............................. 
} 

,使得功能思達接受整數並打印*例如接受3和打印***或接受6和打印******或接受2和打印**。我正在考慮使用for或while循環,並完成任何更好的想法建議?

+3

1.試試您的解決方案。發佈代碼和你有什麼,然後我們可以告訴你是否有更好的方法 – DallaRosa

+0

如果你需要迭代的東西,循環肯定是必要的。任何一個循環語句都很好。順便說一句,當接受2時添加了一個額外的'*'。 – Mahesh

+0

@Mahesh在我看到的編輯中付出很多努力。 ;-) – quasiverse

回答

1

學習,我沒有給出解決方案,提示是使用For或While循環。如果它的工作,它的好,否則張貼您的代碼和問題。

A link to get you started

+1

謝謝大家,但是這個評論對我來說最有幫助!乾杯 – Deepak

2

您可以使用cout.fill

cout.fill('*'); 
cout.width(num); 
cout << ' ' << endl; 

注意,這有很多的東西弄亂,所以你應該捕獲並重置填充和寬度:由於這是爲自己的

char oldfill = cout.fill('*'); 
streamsize w = cout.width(); 
cout.fill('*'); 
cout.width(num); 
cout << ' ' << endl; 
cout.width(w); 
cout.fill(oldfill); 
3

您可以使用std::string

 
using namespace std; 
cout << string(num, '*') << endl; 

或STL的fill_n

 
using namespace std; 
fill_n(ostream_iterator<char>(cout, ""), num, '*');