Read a number starting with 0

Asked

Viewed 428 times

2

I’m having trouble 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 %lli for %llu That already corrects the problem, but I don’t understand why, in fact, when using %llu should be to unsigned long long and not to long long.

  • How can I fix this? I must change to %llu ?

  • 'Cause that’s what happens when you write a number starting with 0?

Code in Ideone

  • 1

    When you start with 0, the remainder of the digits are treated as a number in base 8: https://msdn.microsoft.com/en-us/library/2k2xf226.aspxxx. - and 25 in base 8 is equal to 21 at base 10. Now why it works when it changes to unsigned, that I don’t remember (I need to get back to messing with C...)

  • @hkotsubo When we change to unsigned probably the number is treated as decimal. Thank you

1 answer

4


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

#include <stdio.h>

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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

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

But if you want the 0 even before even there is different.

I’ll say it one more time, number is number. So mathematics defines that zero on the left has no meaning, so it’s ignored.

If you want to read a zero significantly on the left you don’t want to read a number, you want to read a text that has numerical digits. They are completely different concepts. If you want this, then have one read char * with %s, you can put there 0 wherever you want.

Documentation.

  • Yeah, I’ve actually read about %i and %d, but I thought it was mandatory to use the %lli to read a long long

Browser other questions tagged

You are not signed in. Login or sign up in order to post.