简体   繁体   中英

why this C++ program gives incorrect output?

Consider following program:

#include <iostream>
int main()
{
    std::cout<<std::ios::showbase<<123<<", "<<std::hex<<123<<", "<<std::oct<<123<<'\n';
}

Expected Output: 123, 0x7b, 0173

Acquired Output: 512123, 7b, 173 (see live demo here: http://ideone.com/Khzj5j )

But If I modify the above program slightly as following:

#include <iostream>
using namespace std;
int main()
{
    cout<<showbase<<123<<", "<<hex<<123<<", "<<oct<<123<<'\n';
}

Now I got desired output. (see live demo here http://ideone.com/gcuHbm ).

Why first program gave incorrect output but 2nd program doesn't? What's going wrong in first program?

std::ios::showbase is a format flag. std::showbase is a function that takes a std::ios_base and calls ios_base::setf(std::ios::showbase) on it to set the showbase flag.

You use the prior in your first example and the latter in your second example.

#include <iostream>
int main()
{
    std::cout<<std::ios::showbase<<123<<", "<<std::hex<<123<<", "<<std::oct<<123<<'\n';
}

This uses std::ios::showbase ( http://www.cplusplus.com/reference/ios/ios_base/fmtflags/ )

While your other program

#include <iostream>
using namespace std;
int main()
{
    cout<<showbase<<123<<", "<<hex<<123<<", "<<oct<<123<<'\n';
}

Uses std::showbase ( http://en.cppreference.com/w/cpp/io/manip/showbase ) which is why you're getting different results.

Changing the first program to use std::showbase gives you your expected output:

#include <iostream>
int main()
{
    std::cout<<std::showbase<<123<<", "<<std::hex<<123<<", "<<std::oct<<123<<'\n';
}

http://ideone.com/OodBvo

std::ios::showbase is a format flag that has some implementation defined value. When you call std::cout << std::ios::showbase you are displaying that value and not setting the stream format flag.

In you second example you are using std::showbase which sets the format flag of the stream.

In std::ios_base , showbase is a fmtflag that has an implementation-defined value. In this case, it appears to be 512 . On the other hand, there is a stream manipulator (aka, a function) also called showbase , which calls setf(std::ios_base::showbase) . This is defined as a free function in namespace std whereas the fmtflag is a member of std::ios_base .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM