Namespaces
Variants
Views
Actions

std::setw

From cppreference.com
< cpp‎ | io‎ | manip
Revision as of 12:43, 4 December 2012 by P12 (Talk | contribs)

Defined in header <iomanip>
/*unspecified*/ setw( int n );

When used in an expression out << setw(n) or in >> setw(n), sets the width parameter of the stream out or in to exactly n. This value is not "sticky": the next input or output operation that is affected by the value of the stream's width field, resets it to zero (meaning "unspecified").

Contents

Parameters

n - new value for width

Return value

Returns an object of unspecified type such that if str is the name of an output stream of type std::basic_ostream<CharT, Traits> or std::basic_istream<CharT, Traits>, then the expression str << setw(n) or str >> setw(n) behaves as if the following code was executed:

str.width(n);

Example

#include <sstream>
#include <iostream>
#include <iomanip>
 
int main()
{
    std::cout << "no setw:" << 42 << '\n'
              << "setw(6):" << std::setw(6) << 42 << '\n'
              << "setw(6), several elements: " << 89 << std::setw(6) << 12 << 34 << '\n';
    std::istringstream is("hello, world");
    char arr[10];
    is >> std::setw(6) >> arr;
    std::cout << "Input from \"" << is.str() << "\" with setw(6) gave \""
              << arr << "\"\n";
}

Output:

no setw:42
setw(6):    42
setw(6), several elements: 89    1234
Input from "hello, world" with setw(6) gave "hello"

See also

Template:cpp/io/ios base/dcl list widthTemplate:cpp/io/manip/dcl list setfill