2015-10-07 70 views
0

这个想法是打印4个形状,前两个形状打印罚款,接下来两个形状使用setw是为了反射镜,但仍然打印波纹管,因为它们是。C++ 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(); 
} 
+4

你可能包含你的代码的输出,并将其与你想要的输出相比较吗? – FlashDrive

回答

2

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

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

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

+0

我不能格式化输出这个网站的权利,输出只是一个由*构成的三角形,然后翻转(这个作品),然后两个都被镜像 –

0

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

所以,你的内循环(一个循环计数器阴影外一个... 不寒而栗)不能工作打算 - 您需要打印您的外形线条一气呵成的setw()是有效的。这可以用一个相当有用的std::string构造函数来完成:

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

构建串字符ch的数份。如果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 
} 

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

相关问题