Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf vs cin: string as integer processing

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?

like image 957
Valentina Avatar asked Mar 18 '23 16:03

Valentina


1 Answers

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

Since you prefixed 100 with a 0 then it's read as an octal rather than decimal.

Update:

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

* 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.

like image 142
Jonny Henly Avatar answered Mar 31 '23 02:03

Jonny Henly