我有一个输入字符串“0100”
为什么 scanf("%i", &n);
返回 64 而 cin >> n
;给我100?为什么 cin 以十进制值思考,而 scanf 以八进制值思考?
最佳答案
For the
i
specifier: Any number of digits, optionally preceded by a sign (+
or-
). Decimal digits assumed by default (0-9
), but a0
prefix introduces octal digits (0-7
), and0x
introduces hexadecimal digits (0-f
). - scanf - C++ Reference
由于您在 100
前添加了 0
,因此它被读取为八进制而不是十进制。
更新:
Would you mind to add
cin >> setbase(0) >> n
to your answer? - Nicky C
// cin input: 0100
// base | n ='s
// ----------------------
cin >> setbase(0) >> n // *see below | 64
cin >> setbase(8) >> n // octal | 64
cin >> setbase(10) >> n // decimal | 100
cin >> setbase(16) >> n // hexadecimal | 256
* 调用 setbase( x )
其中 x
不等于 8
、10
或 16
与调用 setbase(resetiosflags(ios_base::basefield))
是一样的。 cin
的输入将被读取为 C
文字,这意味着 0
的前缀将是八进制,0x
将是十六进制,没有前缀将是十进制。
关于c++ - scanf 与 cin : string as integer processing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25434026/