Advertisement
Guest User

C++ : Print a square of stars with strings centered inside

a guest
Jan 1st, 2018
643
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. // This code is my answer to an SO question here:
  2. // https://stackoverflow.com/q/48048473/6337519
  3.  
  4.  
  5. #include <iostream>
  6. #include <vector>
  7.  
  8. using std::vector;
  9. using std::string;
  10. using std::cout;
  11. using std::cin;
  12. using std::endl;
  13.  
  14. int main() {
  15.     vector<string> strings;
  16.     cout << "Enter string: ";
  17.     for(;;) {
  18.         string s;
  19.         cin >> s;
  20.         strings.push_back(s);
  21.  
  22.         if(getchar() == '\n')
  23.             break;
  24.     }
  25.     unsigned int n, i, j;
  26.     cout << "Enter size: ";
  27.     cin >> n;
  28.  
  29.     // assuming strings.size() < n
  30.     unsigned int empty_lines_around_text((n - strings.size()) / 2);
  31.     cout << "empty_lines_around_text = " << empty_lines_around_text << endl;
  32.  
  33.     // first horizontal row of stars
  34.     for(j = 0; j < n; ++j)
  35.         cout << '*';
  36.     cout << endl;
  37.  
  38.     for(i = 1; i < empty_lines_around_text; ++i) {
  39.         cout << '*';
  40.         for(j = 1; j < n - 1; ++j) {
  41.             cout << ' ';
  42.         }
  43.         cout << '*' << endl;
  44.     }
  45.  
  46.     //here we do the actual printing of the strings
  47.     for(i = 0; i < strings.size(); ++i) {
  48.         string s = strings[i];
  49.  
  50.         // once again, assuming the size of each string is < n
  51.         unsigned int empty_chars_around_string((n - s.size()) / 2);
  52.         cout << '*';
  53.         for(j = 0; j < empty_chars_around_string; ++j)
  54.             cout << ' ';
  55.         cout << s;
  56.         for(j = empty_chars_around_string + s.size() + 1; j < n - 1; ++j)
  57.             cout << ' ';
  58.         cout << '*' << endl;
  59.     }
  60.  
  61.     for(i = empty_lines_around_text + strings.size() + 1; i < n; ++i) {
  62.         cout << '*';
  63.         for(j = 1; j < n - 1; ++j) {
  64.             cout << ' ';
  65.         }
  66.         cout << '*' << endl;
  67.     }
  68.     // last horizontal line of '*' (we close the square)
  69.     for(j = 0; j < n; ++j)
  70.         cout << '*';
  71.     cout << endl;
  72.  
  73.  
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement