c++程序接受int和打印*

C++ program to accept int and print *

本文关键字:打印 int 程序 c++      更新时间:2023-10-16

我正在自学c++,我正在考虑一个简单的程序来适应语法。

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

这样printStar函数接受一个整数并打印*,例如接受3并打印***或接受6并打印******或接受2并打印**。我正在考虑使用for或while循环,并得到它做任何更好的想法建议?

您可以使用std::string:

<>之前使用命名空间std;cout & lt; & lt;字符串(num, '*') <<endl;之前

或STL的fill_n:

<>之前使用命名空间std;fill_n (ostream_iterator (cout, " "), num,‘*’);

您可以使用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);

因为这是为了你自己的学习,我没有给出一个解决方案,一个提示是使用for或While循环。如果它能工作,那很好,否则就把你的代码和问题贴出来。

入门链接