Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading