cs50/pset1/credit Can't figure out how to use a digit counter without changing the initial variable

The digit counter works, displaying thhe correct number of digits, however my variable (number) changes from the initial input. I need it to stay the same because I use it later on in he code to test what type of card it is. Here is an example input and output.

/workspaces/cs50/credit/ $ ./credit
Number?
378282246310005
dcounter, 15
num1, 0
number, 12600566272504165

I can’t figure out why number changes away from 378282246310005.

Here is the section of code in question…

//Asks the user for the card number
long number;
long num1;
    do
    {
        number = get_long("Number?\n");

    }
    while (number < 1 || number > 9999999999999999);

    num1 = number;
//Counts the digits the card has
int dcounter = 0;
    while (num1 != 0)
    {
        num1 /= 10;
        dcounter++;
    }

    printf("dcounter, %i\n", dcounter);
    printf("num1, %lo\n", num1);
    printf("number, %lo\n", number);

I want number to stay 378282246310005 after the digit counter runs. I think using the numc variable in the dcounter should do that, but alas it did not. Very new coder and been stuck on this for hours.Could it be a limitation of the long type?

>Solution :

You are using printf with the %o formatter (modified by l for long).

That prints out numbers in Octal (base-8) format.

Why are you changing from Decimal (base-10) to Octal format?
Do you get the proper output if you use %ld (long decimal integer format)?

See this code for demonstration:

#include <stdio.h>

int main(void)
{
    long number = 378282246310005;
    long num1   = number;
    
    //Counts the digits the card has
    int dcounter = 0;
    while (num1 != 0)
    {
        num1 /= 10;
        dcounter++;
    }

    printf("dcounter, %i\n", dcounter);
    printf("num1, %lo\n", num1);
    printf("number (octal), %lo\n", number);
    printf("number (dec), %ld\n", number);
    
    return 0;
}

Output:

dcounter, 15
num1, 0
number (octal), 12600566272504165
number (dec), 378282246310005

https://ideone.com/oTEw7B

Leave a Reply