【问题标题】:c++ setw not working the way I need it to [closed]c ++ setw无法按照我需要的方式工作[关闭]
【发布时间】:2015-10-07 06:25:28
【问题描述】:

这个想法是打印 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();
}

【问题讨论】:

  • 您能否将代码的输出包含在内并将其与您想要的输出进行比较?

标签: c++ setw


【解决方案1】:

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

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

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

【讨论】:

  • 我不能为这个网站格式化输出,输出只是一个由 * 组成的三角形,然后翻转(这个工作),然后两者都被镜像
【解决方案2】:

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

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

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

用字符 ch 的 count 个副本构造字符串。如果 count >= 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
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多