在C ++中不使用循环,递归或goto打印字符n次
在本节中,我们将看到如何在C++中不使用循环和递归地打印字符n次。我们可以通过使用字符串类构造函数来解决此问题。有一个构造函数,我们在其中构造将被多次打印的字符以及将被打印的次数。
范例程式码
#include <iostream>
using namespace std;
void print_char_n_times(char my_char, int count) {
cout << string(count, my_char) << endl;
}
int main() {
//打印字符B10次
print_char_n_times('B', 10);
//打印字符x30次
print_char_n_times('x', 30);
}输出结果
BBBBBBBBBB xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx