C++ output * table

C++ output * table

本文关键字:table output C++      更新时间:2023-10-16

我正在尝试在C++中创建一个表格,要求您提供边的长度并输出一个星形表。

有人可以指出我应该做什么才能让表格开始正确显示的正确方向吗?

输入:

Enter length of side: 5

想要的输出:

*****
*   *
*   *
*   *
*   *
*****

到目前为止,我输出 * 减去 1 的第一行,然后显示您输入的数字。

#include "main.h"
using namespace std;

    int main () {
      int sideLength;
      cout << "Enter lengh of side: ";
      cin >> sideLength;
      cout.fill('*');
      cout.width(sideLength);
      cout << sideLength << endl;
      return 0;
    }

感谢高级,只是学习C ++

我还不太可爱。也许我可以想出更好的东西...

#include <iostream>
#include <algorithm>
#include <iterator>
int main()
{
    int size;
    if (std::cin >> size) {
        auto to(std::ostreambuf_iterator<char>(std::cout));
        auto line([=](decltype(to) to){ return std::fill_n(to, size, '*'); });
        auto box([=](decltype(to) to){
                *to++ = '*'; std::fill_n(to, size - 2, ' '); *to++ = '*'; return to;
            });
        *(to = line(to))++ = 'n';
        for (int i(1); ++i < size; ) {
            *(to = box(to))++ = 'n';
        }
        *(to = line(to))++ = 'n';
    }
}

你可以这样做:

#include <iostream>
using namespace std;
int main () {
  int sideLength;
  cout << "Enter lengh of side: ";
  cin >> sideLength;
  for (int i = 0; i < sideLength; i++)
    cout<<"*";
  cout<<"n";
  for (int i = 0; i < sideLength-2; i++) 
  {
    cout<<"*";
    for (int j = 0; j < sideLength-2; j++)
      cout<<" ";
    cout<<"*"<<"n";
  }
  for (int i = 0; i < sideLength; i++)
    cout<<"*";
  cout<<"n";
  return 0;
}

您还应该添加一个循环来打印侧面和底部。
建议:

for (int i=0; i <= sideLength; i++)  
{
cout<<endl <<"*";
for (int j=0; j < sideLength;j++) 
{
cout<<" ";
cout<<"*";
}
cout.fill('*');

在 cout.fill('*') 行之后添加这些行。
也许它会起作用。