user7140484 user7140484 - 13 days ago 10
C++ Question

Why std::uppercase doesn't work with strings?

I've been using manipulators for some time without fully understand how they work.

This code:

std::cout << std::hex << std::showbase;
std::cout << std::uppercase << 77 << '\n';
std::cout << std::nouppercase << 77 << '\n';


Or alternatively this:

std::cout << std::hex;
std::cout << std::setiosflags(std::ios::showbase | std::ios::uppercase) << 77 << '\n';
std::cout << std::nouppercase << 77 << '\n';


Both outputs this:

0X4D // 'X' and 'D' uppercase
0x4d // 'x' and 'd' lowercase


However none of the following lines of code can convert the string "abcd" to uppercase. Why?

std::cout << std::uppercase << "abcd" << '\n';
std::cout << std::setiosflags(std::ios::uppercase) << "abcd" << '\n';


Another question is why
showbase
and
uppercase
must be qualified with
std::ios::
inside
std::setiosflags()
and only with
std::
outside that function?

Finaly, why
std::hex
can't be accepted inside
std::setiosflags()




Thank you

Answer

Read the documentation for std::uppercase.

Enables the use of uppercase characters in floating-point and hexadecimal integer output.

std::ios_base::hex is accepted by std::setiosflags there is an example in the docs.

Here is the example for std::uppercase:

#include <iostream>
int main()
{
    std::cout << std::hex << std::showbase
              << "0x2a with uppercase: " << std::uppercase << 0x2a << '\n'
              << "0x2a with nouppercase: " << std::nouppercase << 0x2a << '\n'
              << "1e-10 with uppercase: " << std::uppercase << 1e-10 << '\n'
              << "1e-10 with nouppercase: " << std::nouppercase << 1e-10 << '\n';
}

Here is the example for std::setiosflags:

#include <iostream>
#include <iomanip>

int main()
{
    std::cout <<  std::resetiosflags(std::ios_base::dec) 
              <<  std::setiosflags(  std::ios_base::hex
                                   | std::ios_base::uppercase
                                   | std::ios_base::showbase) << 42 << '\n';
}

The definitions:

std::hex is defined as std::ios_base& hex( std::ios_base& str );

std::ios_base::hex is defined as static constexpr fmtflags hex = /*...*/;