Phần này trình bày cách in một ký tự n lần mà không dùng vòng lặp, đệ quy hay goto trong C++. Ta khai thác constructor của lớp string: string(count, ch) tạo chuỗi gồm count ký tự ch.
Ví dụ minh họa
#include <iostream>
using namespace std;
void print_char_n_times(char my_char, int count) {
cout << string(count, my_char) << endl;
}
int main() {
print_char_n_times('B', 10); // In 'B' 10 lần
print_char_n_times('x', 30); // In 'x' 30 lần
}
Kết quả
BBBBBBBBBB xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx