C ++设置没有按照我需要的方式工作
c++ setw not working the way I need it to
这个想法是打印 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
(来进一步简化,但我想保持接近您的原始代码。
相关文章:
- 以螺旋方式打印矩阵的程序.(工作不好)
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 如何解决在负数的情况下程序以相同方式工作的问题?
- 在 Eclipse 中添加库的工作方式是否与在 Visual Studio 中相同?
- 适用于 macOS 的 Xcode 应用程序。这就是我设置从USB麦克风输入获取音频的方式。一年前工作,现在没有了。为什么
- 我的随机生成器是否不工作,或者我决定人/骨架是否击中对手的方式是否有错误
- OpenGL应用程序在不同的计算机上的工作方式不同
- >= <= 没有按照我使用它们的方式工作,我在哪里搞砸了?
- 程序按执行方式工作,直到我向其添加析构函数为止
- 简单的计数和求和函数没有按照我预期的方式工作
- 任何人都有任何想法编写与C 旧手机中的消息作曲家以相同方式工作的程序
- C++ int x++ 和 int ++x 无法按照我想象的方式工作
- 重载输入/输出运算符,为什么它以这种方式工作而不是以另一种方式工作
- 我正试图在我的SFML Platformer中实现双跳,但它并没有按预期的方式工作
- 比率类中的运算符/=以错误的方式工作
- 怪物阵列没有按我需要的方式工作
- C ++设置没有按照我需要的方式工作
- 为什么这段代码以相反的方式工作?
- 为什么情绪分类不能按照 openCV 链接中指定的方式工作?
- 如果两者都以相同的方式工作,那么使用 void func(struct myStruct s) 和 void func(myStruct s) 有什么区别?