Use ostream with bases other than 8, 10 and 16
Asked Answered
N

2

7

I have a polynomial class, and its natural representation is its coefficients. If a coefficient is set, then its a 1 for binomial basis, 1 or 2 for trinomial basis, etc. For example, in a binomial basis, X2 + 1 is represented as 101; and in a trinomial basis, 2X2 + 1 is represented as 201.

The class provides an operator<< overload. Internally, the class represents the coefficients using an integral array. So I should be able to perform:

ostringstream oss;
for (size_t i=0; i<v.size(); i++)
   oss << v[i];

The problem I am having is I don't know how to configure the ostream for bases other than 8, 10 and 16. ios_base provides std::oct, std::dec and std::hex for the popular bases, but I don't see what to use for the less frequently used bases. And pages like C++ Reference on ios_base does not discuss what to use.

How do I use ostream with bases other than 8, 10 and 16?

Needleful answered 11/11, 2015 at 21:32 Comment(6)
No, there is no support for other bases. You have to convert it to a string and output that.Cachalot
Not sure if this is possible using standard means. Looking at en.cppreference.com/w/cpp/io/manip/setbase - "Values of base other than 8, 10, or 16 reset basefield to zero, which corresponds to decimal output and prefix-dependent input."Calaboose
Unless something I don't know about has been added very recently, there is no support for bases other than 8, 10, and 16 in iostreams. You're going to have to read numbers as strings and decode them by hand.Muna
@jww "And pages like C++ Reference on ios_base does not discuss what to use." Use a better reference.Kippy
@πάντα - Thanks. Unfortunately, CPP Reference on ios_base does not discuss what to use, either.Needleful
@Needleful There isn't a standard way of doing this.Calaboose
C
4

I don't think this is possible using standard means. Looking at std::setbase

Values of base other than 8, 10, or 16 reset basefield to zero, which corresponds to decimal output and prefix-dependent input.

Calaboose answered 11/11, 2015 at 21:55 Comment(0)
I
0

Replacing my answer since the direction was backwards. See itoa. The documentation says that it is a non standard function. Since this is a non standard function, stackoverflow has some implementations in the page.

Insignificant answered 11/11, 2015 at 21:38 Comment(3)
Unfortunately the OP asks for the other way round. They'll need to provide their own IO-manipulator. Of course this implementation should yield a string representation confirming to what stoi() is able to convert to a number again.Kippy
setbase does not appear to work as expected. From the cited page: "...Values of base other than 8, 10, or 16 reset basefield to zero, which corresponds to decimal output and prefix-dependent input."Needleful
@πάνταῥεῖ. Fixed my answer. Thanks for the heads up.Insignificant

© 2022 - 2024 — McMap. All rights reserved.