2010-09-20 89 views
-1
inpfile>>ch; 

if(ch<16) outfile<<"0×0"<<std::hex<<setprecision(2)<<(int)ch<<" "; 

std::hex<<setprecision(2)是什么意思?如何理解下面的C++代码?

+3

谷歌是你的朋友:HTTP ://www.cplusplus.com/reference/iostream/manipulators/hex/ http://www.cplusplus.com/reference/iostream/manipulators/setprecision/ – meagar 2010-09-20 16:26:04

+0

@meagar:IIUC,SO的目标是成为谷歌当有人提出一个与编程有关的问题时指出。为了这个工作,这些问题必须首先在这里提出并回答。 – sbi 2010-09-20 16:29:32

+1

@sbi在问题变得过于接近“你会为我做我的想法吗?”时,必须切断一些东西,并且在我看来,这个问题是避开这条线的。 SO应该是Google指出的*有价值的问题,而不是文档最好回答的简单问题。否则,我们可能只是镜像文档并完成它。 – meagar 2010-09-21 14:47:00

回答

2

iostream s时,可以操纵达到预期的格式 - 这是由什么一见钟情的样子,如图我们的代码主题行输出到它们的预定值来完成。

std::hex在base16中显示以下整数值。

setprecision设置显示下列浮动值的精度。

毛皮上操纵进一步信息,启动here

0

std::hex将输出基地设置为十六进制。

setprecision对此行没有影响,因为它仅影响浮点数。

1

是什么std::hex<<setprecision(2)是什么意思?

std::hexstd::setprecision都是所谓操纵。应用于流(通过输出它们完成),它们操纵流,通常用于更改流的格式。特别是,std::hex操纵流,以便值以十六进制写入,std::setprecision(x)操作它以输出带有x数字的数字。
(A,而流行的机械手,你可能已经知道是std::endl。)

正如你所看到的,有带参数的操纵和那些需要没有。另外,大多数(原则上全部)操纵器都是粘性的,这意味着它们对流的操纵持续直到它被明确地改变。 Here是一个关于这个话题的广泛讨论。

+0

+1有关粘性的信息 – 2010-09-20 16:58:20

1

这条线是一样的:

char ch; 
inpfile>>ch; 

if(ch<16) 
{ 
    outfile  << "0×0"    // Prints "0x0" (Ox is the standard prefix for hex numbers) 
    /*outfile*/ << std::hex   // Tells the stream to print the next number in hex format 
    /*outfile*/ << setprecision(2) // Does nothing. Presumably they were trying to indicate print min of 2 characters 
    /*outfile*/ << (int)ch   // Covert you char to an integer (so the stream will print it in hex 
    /*outfile*/ << " ";    // Add a space for good measure. 
} 

不是setprecision(2)什么,可能是为了为运输及工务局局长(2)< < setfill( '0')