C ++设置没有按照我需要的方式工作

c++ setw not working the way I need it to

本文关键字:方式 工作 设置      更新时间:2023-10-16

这个想法是打印 4 个形状,前两个形状打印得很好,接下来的两个形状使用 setw 是镜像,但仍然按原样打印。

我的理解是setw制作了一种文本框,从参数中指定的文本位置从右到左开始输出,它适用于我尝试过的其他示例。但是由于某种原因,当通过这些 for 循环时,它只是添加设置数量的制表符空间并在 setw 位置的错误一侧打印。

#include <conio.h>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
   int x = 1;
   for (int i = 0; i < 9; i++)
   {
      for (int i = 1; i <= x; i++)
         cout << "*";
      x++;
      cout << endl;
   }
   cout << endl;
   x = x - 1;
   for (int i = 0; i < 9; i++)
   {
      for (int i = 1; i <= x; i++)
         cout << "*";
      x--;
      cout << endl;
   }
   cout << endl;
   for (int i = 0; i < 9; i++)
   {
      cout << setw(10);
      for (int i = 1; i <= x; i++)
         cout << "*";
      x++;
      cout << endl;
   }
   cout << endl;
   for (int i = 0; i < 9; i++)
   {
      cout << setw(10);
      for (int i = 1; i <= x; i++)
         cout << "*";
      x--;
      cout << endl;
   }
   _getch();
}

我无法看到您的输出,但此信息可能会有所帮助。

setw用于指定下一个数字或字符串值的最小空间。这意味着如果指示的空格大于数值或字符串的空格,它将添加一些填充。

最重要的是setw不会改变输出流的内部状态,因此它只确定下一个输入的大小,这意味着它仅适用于 for 循环的第一次迭代。

setw()一次,然后输出x次。 setw()只影响下一个输出,即第一个字符 - 按照您的指示从右到左设置 - 其余字符附加到它。

所以你的内循环(有一个循环计数器遮蔽外部循环......不寒而栗(无法按预期工作 - 您需要一次性打印形状线才能setw()有效。这可以通过一个相当有用的std::string构造函数来完成:

basic_string( size_type count,
              CharT ch,
              const Allocator& alloc = Allocator() );

使用字符 ch 的计数副本构造字符串。如果计数>= npos,则行为未定义。

(来源:cppreference.com(

然后是第三个形状比其他形状少一条线的问题。

固定代码:

#include <iostream>
#include <iomanip>
#include <string>
// <conio.h> is not available on non-Windows boxes,
// and if MSVC were smart enough to keep the console
// window open, this kludge wouldn't be necessary
// in the first place.
#ifdef _WIN32
#include <conio.h>
#endif
using namespace std;
int main()
{
   int x = 1;
   for (int i = 0; i < 9; i++)
   {
      cout << string( x, '*' ) << "n";
      x++;
   }
   cout << endl;
   x = x - 1;
   for (int i = 0; i < 9; i++)
   {
      cout << string( x, '*' ) << "n";
      x--;
   }
   cout << endl;
   for (int i = 0; i < 9; i++)
   {
      // increment first, or the loop will not print
      // the last line, making the third shape different.
      x++;
      cout << setw(10) << string( x, '*' ) << "n";
   }
   cout << endl;
   for (int i = 0; i < 9; i++)
   {
      cout << setw(10) << string( x, '*' ) << "n";
      x--;
   }
#ifdef _WIN32
   _getch();
#endif
}

这可以通过创建一个string然后在每个循环中打印其子字符串(而不是每次都创建新的临时string(来进一步简化,但我想保持接近您的原始代码。

相关文章: