[英]why this C++ program gives incorrect output?
考虑以下程序:
#include <iostream>
int main()
{
std::cout<<std::ios::showbase<<123<<", "<<std::hex<<123<<", "<<std::oct<<123<<'\n';
}
预期输出:123、0x7b、0173
获得的输出:512123、7b、173(在此处查看现场演示: http ://ideone.com/Khzj5j)
但是如果我稍微修改上面的程序如下:
#include <iostream>
using namespace std;
int main()
{
cout<<showbase<<123<<", "<<hex<<123<<", "<<oct<<123<<'\n';
}
现在我得到了想要的输出。 (在此处查看现场演示http://ideone.com/gcuHbm )。
为什么第一个程序给出了错误的输出,而第二个程序却没有? 第一个程序出了什么问题?
std::ios::showbase
是格式标志。 std::showbase
是一个函数,它采用std::ios_base
并在其上调用ios_base::setf(std::ios::showbase)
以设置showbase
标志。
您在第一个示例中使用先验,在第二个示例中使用后者。
#include <iostream>
int main()
{
std::cout<<std::ios::showbase<<123<<", "<<std::hex<<123<<", "<<std::oct<<123<<'\n';
}
这使用std::ios::showbase
( http://www.cplusplus.com/reference/ios/ios_base/fmtflags/ )
而你的其他程序
#include <iostream>
using namespace std;
int main()
{
cout<<showbase<<123<<", "<<hex<<123<<", "<<oct<<123<<'\n';
}
使用std::showbase
( http://en.cppreference.com/w/cpp/io/manip/showbase ) 这就是你得到不同结果的原因。
更改第一个程序以使用std::showbase
为您提供预期的输出:
#include <iostream>
int main()
{
std::cout<<std::showbase<<123<<", "<<std::hex<<123<<", "<<std::oct<<123<<'\n';
}
std::ios::showbase
是一个格式标志,具有一些实现定义的值。 当您调用std::cout << std::ios::showbase
您正在显示该值而不是设置流格式标志。
在第二个示例中,您使用std::showbase
设置流的格式标志。
在std::ios_base
, showbase
是具有实现定义值的fmtflag
。 在这种情况下,它似乎是512
。 另一方面,还有一个流操纵器(又名函数)也称为showbase
,它调用setf(std::ios_base::showbase)
。 这被定义为namespace std
的自由函数,而fmtflag
是std::ios_base
的成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.