简体   繁体   中英

C++: setw and setfill not behaving predictably

From my understanding, setw(n) acts by creating a width of n number of characters. On the other hand, setfill('x') allows us to print an n number of x characters.

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):

//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. 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. 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.

Solution would be to use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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