I have a very strange question which stems from a bug of a C++11 program I have been writing.
See the following code:
long long a[1000];
int main(int argc, char * argv[]) {
for(long long i = 0; i < 300; ++i) {
scanf("%lli", &a[i]);
std::cout << a[i] << std::endl;
}
return 0;
}
Trying the inputs 1
, 2
etc we get outputs 1\n
, 2\n
, etc. like expected. This also works for inputs like 001
where we get 1\n
, 0004
where we get 4\n
.
However when the digit after the leading zeros is an 8 or 9, the scanf()
reads the leading zeroes first, then reads the digits after.
For example:
Input: 0009
, output: 000\n9\n
.
Input: 08
, output 0\n8\n
.
Input: 00914
, output 00\n914\n
.
I've done some testing and for these cases it seems the scanf()
reads the leading zeros first, and the remaining digits are left in the buffer, which are picked up on the second run of the loop.
Can someone hint at what is going on?
I am using XCode 11.3.7 and compiling with Clang C++11. (I haven't messed with the project settings)
Thank you in advance!!!
Use %lld
instead of %lli
.
The reason %i
doesn't work is because 0
is interpreted as a prefix for octal numbers, and the digits 8
and 9
don't exist in octal:
d
Matches an optionally signed decimal integer; the next pointer must be a pointer to int.
i
Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, and in base 10 otherwise. Only characters that correspond to the base are used.
You would also get the wrong answer for other numbers, e.g. 010
in octal would be parsed as 8.
Or, even better: use C++ instead of C.
std::cin >> a[i];