C ++ about the format of output text strings

2

is my first question in the forum.

I come from a past in the programming in C "plain" for saying it in some way. Now I have a linux mint installed and I'm using g ++ to learn C ++ and a couple of books and tutorials.

Here the output format of the character strings and the "ios" plays a role. We have an ios :: hex and the cout.setf () method and what I do is this:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int val = 128;
    cout.setf(ios::hex);
    cout << val << endl;
    return 0;
}

It shows me at the terminal exit "128" and not 80 as it should be. How do I display a hexadecimal number in the console via std :: cout? I would also like to know how to narrow the output for example if I show 1 byte that shows "80" and if I show 2 bytes that shows "0080".

    
asked by Lucas 14.12.2017 в 01:48
source

1 answer

4

You have to use the flag std::ios::basefield , this will only show the value as hexadecimal, to place the zeros you must first set a width with std::setw() , and then fill it with std::setfill('0') :

#include <iostream>
#include <iomanip>

int main()
{
    int val = 128;
    std::cout.setf(std::ios::hex);
    std::cout << val << std::endl;
    std::cout.setf(std::ios::hex, std::ios::basefield);
    std::cout << val << std::endl;
    std::cout << std::setw(4) << val << std::endl;
    std::cout << std::setfill('0') << std::setw(4) << val << std::endl;
    return 0;
}

Exit:

128
80
  80
0080
    
answered by 14.12.2017 / 02:35
source