c++ - scanf 与 cin : string as integer processing

标签 c++ scanf cin visual-c++-2010

我有一个输入字符串“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 a 0 prefix introduces octal digits (0-7), and 0x 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 不等于 81016 与调用 setbase(resetiosflags(ios_base::basefield)) 是一样的。 cin 的输入将被读取为 C 文字,这意味着 0 的前缀将是八进制,0x 将是十六进制,没有前缀将是十进制。

关于c++ - scanf 与 cin : string as integer processing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25434026/

相关文章:

c++ - 在嵌套函数模板中使用模板类型名

c++ - STL push_back 优化导致数组下标超出数组边界

c++ - 是否可以在一个语句中创建一个对象并调用一个方法?

C 输入问题

c - 在 C 中没有附加参数的 scanf

c - scanf() 在 for 循环中被跳过

c++ cin >> 套接字样式函数

c++ - 在cpp中找出图像中对象的尺寸

c++ - 为什么 cout 不起作用?

c++ - 某些测试的输入验证未按预期工作