I have an input string "0100"
Why does scanf("%i", &n); returns 64 and cin >> n; gives me 100? Why does cin think in decimal values and scanf in octal?
For the
ispecifier: Any number of digits, optionally preceded by a sign (+or-). Decimal digits assumed by default (0-9), but a0prefix introduces octal digits (0-7), and0xintroduces hexadecimal digits (0-f). - scanf - C++ Reference
Since you prefixed 100 with a 0 then it's read as an octal rather than decimal.
Would you mind to add
cin >> setbase(0) >> nto 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
* Calling setbase( x ) where x does not equal 8, 10 or 16 is the same thing as calling setbase(resetiosflags(ios_base::basefield)). Where the input to cin would be read as a C literal, meaning the prefix of 0 would be octal, 0x would be hex and no prefix would be decimal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With