简体   繁体   English

C ++:setw和setfill行为异常

[英]C++: setw and setfill not behaving predictably

From my understanding, setw(n) acts by creating a width of n number of characters. 据我了解,setw(n)通过创建n个字符的宽度来起作用。 On the other hand, setfill('x') allows us to print an n number of x characters. 另一方面,setfill('x')允许我们打印n个x字符。

I am trying to get two rows of stars, like this: 我正在尝试获得两排星星,像这样:

**************************************
Woohoo stars!
**************************************

In addition, I would like to create two lines of dots of equal length on both sides of a string, like this: 另外,我想在字符串的两侧创建两行等长的点,如下所示:

....................... TEAR HERE .......................

Instead, I am getting something like this: 相反,我得到这样的东西:

Woohoo stars!
**************************************

.............. TEAR HERE .............................

To achieve these goals, I am using the code below with #include<iomanip> (note: it is being printed to an external .txt file): 为了实现这些目标,我将以下代码与#include<iomanip> (注意:它正在打印到外部.txt文件中):

//goal 1
outfile << setw(40)<<setfill('*') << endl;  
outfile<< "Woohoo stars!" << endl; 
outfile << setw(40)<<setfill('*') << endl; 

//goal 2
outfile <<setfill('.')<< setw(30) " TEAR HERE " << setfill('.')<< setw(30) <<endl;  

I have tried reversing the order of setw and setfill on purpose, but it resulted in the same effect after it was compiled. 我尝试过setfill逆转setwsetfill的顺序,但是在编译后产生了相同的效果。 Furthermore, for the star pattern, the top row does not even get outputted for some reason. 此外,对于星形模式,由于某种原因,甚至没有输出第一行。 Finally, I made sure to do these commands on a new line, so there wouldn't be anything else interfering with the lines they are on. 最后,我确保在新的一行上执行这些命令,因此不会有其他干扰它们的行。

No, setw(n) does not "create a width of n number of characters", it will pad next printed item to n width using specified fill character. 不, setw(n)不会“创建n个字符的宽度”,它将使用指定的填充字符将下一个打印的项目填充到n个宽度。 You can still make it work like you expected by printing empty string: 您仍然可以通过打印空字符串来使其按预期工作:

outfile << setw(40)<<setfill('*') << "" << endl;

setw actually just sets the width of the next thing written to the stream, so the "Tear Here" will be right aligned in a field of width 30. setw实际上只是设置写入流中的下一个对象的宽度,因此“ Tear Here”将在宽度为30的字段中右对齐。

Solution would be to use: 解决方法是使用:

outfile <<setfill('.')<< setw(30) << '.' << " TEAR HERE " << setfill('.')<< setw(30) << '.' <<endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM