jackycflau
jackycflau

Reputation: 1121

The meaning of ios:: in std::ios::fixed

Consider the following code:

using namespace std;

cout.setf(ios::fixed);
cout.precision(2);

The above codes are used to round the output to the 2 decimal places.

I am not very familiar to the library thingy. What is the meaning of ios:: written before the fixed? Why do we need to add ios:: instead of typing fixed? In other words, can anyone explain the meaning of std::ios::fixed and if I use std::fixed, that would be wrong? ios:: is not a namespace, right?

Upvotes: 0

Views: 4049

Answers (3)

Tony Delroy
Tony Delroy

Reputation: 106126

ios is a typedef...

typedef basic_ios<char> ios;

...which specifies a basic_ios instantiation to handle operations on char types.

So, for example, std::ios::X works for char, while std::basic_ios<wchar_t>::X aka std::wios::X works for "wide" characters (e.g. capable of encoding more symbols / non-English languages etc.). In the case of X==fixed, they're the same constant inherited from std::ios_base's fmtflags, but the freedom is there for the implementation to do whatever's best to support those different char_types in the members that aren't inherited from the common base, such as .good(), .eof(), .clear(), fill(), narrow() etc. - see here.

For convenience, you can simply use cout << std::fixed << std::setprecision(2) << my_data...;, rather than directly calling cout.setf with the flag values.

Upvotes: 1

T.C.
T.C.

Reputation: 137345

ios is an alias for basic_ios<char>. ios::fixed refers to a member constant of that class called fixed, which it actually inherits from the class ios_base, which is a common base class for all iostream classes, so all of ios_base::fixed, ios::fixed, fstream::fixed, istringstream::fixed, and cout.fixed refer to the same thing.

std::fixed is a manipulator that sets the fixed flag when used on a stream like stream << std::fixed, provided for convenience.

Upvotes: 1

user5349065
user5349065

Reputation: 11

fixed exists both as a manipulator (a function) in namespace std, but also as a static constexpr fmtflags in std::ios_base. std::ios is just a typedef for std::basic_ios<char>, which in turn is derived from std::ios_base. In other words, it inherits the member variable fixed. Note that the manipulator does what you do manually:

// Same as std::cout << std::fixed 
std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);

Upvotes: 1

Related Questions