Read a number starting with 0

2

I'm having problems reading a number initialized with long long

long long valid;
scanf("%lli", &valid);

INPUT:

025

The variable valid will have as content 21 and not 25

If I change from %lli to %llu this already fixes the problem, but I do not understand why, by using %llu it should be unsigned long long and not long long . >

  • How to fix this? Will I have to change to %llu ?

  • Why does this happen when we write a number starting with 0 ?

Ideone Code

    
asked by anonymous 24.08.2018 / 15:55

1 answer

4

If you want to ignore the zero you must read decimal, and this is used %d , and for being long long to be %lld :

#include <stdio.h>

int main(void) {
    long long valid;
    scanf("%lld", &valid);
    printf("%lld", valid);
}

%lli says that it wants a number, no matter the notation typed, and when it starts with zero it understands that it is octal. In almost all cases, the %i is an error.

But if you want 0 even before it's even there, it's different.

I'll repeat it again, number is number. So math defines that zero on the left has no meaning, so it's ignored.

If you want to read a leading zero significantly you do not want to read a number, you want to read text that has numeric digits. They are completely different concepts. If you want to do this, then read char * with %s , then you can 0 where you want.

Documentation .

    
24.08.2018 / 16:03