Why cant this work

closed account (28poGNh0)
/// Why cant this work

Edit Sorry I forget to tag code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# include <iostream>
# include <iomanip>
using namespace std;

ostream &manip(ostream &stream)
{
    cout.setf(ios::showpos);// Works fine
    cout.setf(ios::hex);// Does not work

    return stream;
}

int main()
{
    int nbr;
    cin >> nbr;

    cout << manip << nbr << endl;

    return 0;
}
Last edited on
closed account (o3hC5Di1)
Hi there,

For completeness, I'll ask you to wrap your code with [code][/code] tags - but I gave you the link describing how to do so in another topic.

The reason this won't work is because of this line:

cout << manip << nbr << endl;

First, manip is a function taking an argument, so it should be: manip(cout);
Second, you are returning a reference to the stream, so the cout object thinks you're wanting to print the address of the stream to the screen.

The insertion operator << is actually a member function of ostream: http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/
So what actually happens in succession here is:

1
2
3
cout.operator<<(manip);
cout.operator<<(nbr);
cout.operator<<(endl);


Also, you are using the setf() function not entirely correct: http://www.cplusplus.com/reference/ios/ios_base/setf/
You need to do:

cout.setf(ios::hex, ios::basefield);

Working example: http://coliru.stacked-crooked.com/a/06a5747841345c6b

All the best,
NwN
Last edited on
closed account (28poGNh0)
Thanks for the repley

I did that
I entered the number 55 It outputs
0x4740c455
I expecting 37 as a hex number

Can you give me an entire expamle ?
closed account (o3hC5Di1)
Hi,

Sorry, I've edited my previous post because I made a mistake.
The post should now provide the correct information regarding the problem.

All the best,
NwN
It is not going to work. Hexadecimal numbers are not usually considered signed, so you won't see the plus or minus signs.

Also, you should be setting the flags on the stream argument, not on cout.

To get what you want, you'll need a little more manipulator fun help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# include <iostream>
# include <iomanip>
using namespace std;

struct manip
{
    int value;
    manip(int value): value(value) { }
};

ostream &operator << (ostream &outs,const manip &value)
{
    int  v = value.value;
    char c = '+';
    if (v < 0)
    {
        v = -v;
        c = '-';
    }
    ios::fmtflags flags = outs.setf(ios::hex,ios::basefield);
    outs << c << v;
    outs.setf(flags);
    return outs;
}

int main()
{
    int nbr;
    cin >> nbr;

    cout << manip(nbr) << endl;

    return 0;
}

Hope this helps.
closed account (28poGNh0)
@Duoas, always honnored to read your posts,thanks hope you read my next advance(probably) post,thanks again

also thanks @NwN you being a lot helpful this day
Topic archived. No new replies allowed.