c++ - How does std::setw work with string output? -
i trying use set width setw
string output output file, however, not able make work. have me following example.
// setw example #include <iostream> #include <iomanip> #include <fstream> int main () { std::ofstream output_file; output_file.open("file.txt"); output_file << "first" <<std::setw(5)<< "second"<< std::endl; output_file.close(); return 0; }
edit: above lines expected have many spaces between first
, second
, first second
i hardly see spaces, output comes firstsecond
think missed working of setw()
note: integers, works fine just:
output_file << 1 <<std::setw(5)<< 2 << std::endl;
what doing wrong??.
i suspect understanding of std::setw
not correct. think need more along lines of combination of:
std::setw
setting field widthstd::setfill
setting fill characterstd::left
,std::right
,std::internal
setting write position within specified field width.
what happening in code:
- uses
std::setw(5)
establish field width of 5 characters. - sends
"first"
stream, 5 characters long, established field width consumed. no additional filling takes place. - sends
"second"
stream, 6 characters long, again, entire field width consumed (and in-fact breached). again, no filling takes place
if you're intent have (with column numbers above show positions):
col: 0123456789012345678901234567890123456789 first second third fourth
notice how each word starts on multiple of 10 boundary. 1 way using :
- a output position
std::left
(so fill, if goes on right achieve desired width). default strings, never hurts sure. - a fill character of
std::setfill(' ')
. again, default. - a field width
std::setw(10)
why such large number? see below
example
#include <iostream> #include <iomanip> int main () { std::cout << std::left << std::setfill(' ') << std::setw(10) << "first" << std::setw(10) << "second" << std::setw(10) << "third" << std::setw(10) << "fourth" << '\n'; return 0; }
output (column numbers added)
0123456789012345678901234567890123456789 first second third fourth
so happens if change output location std::right
? well, identical program, changing first line :
std::cout << std::right << std::setfill(' ')
we get
0123456789012345678901234567890123456789 first second third fourth
finally, 1 constructive way of seeing fill characters being applied changing fill char visible (ie. besides space). last 2 examples output, changing fill char std::setfill('*')
produces following output:
first
first*****second****third*****fourth****
second
*****first****second*****third****fourth
notice in both cases, since none of individual output items breached std::setw
value, total output line size each same. changed fills applied , output aligned within std::setw
specification.
Comments
Post a Comment