不使用 C++ 中的迴圈、遞迴或轉到列印字元 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() { //print character B 10 times print_char_n_times('B', 10); //print character x 30 times print_char_n_times('x', 30); }
輸出
BBBBBBBBBB xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
廣告