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

Checking if an input is a digit and converting to an ascii character in C?

Currently stuck on a uni problem. (Language is C)

The prompt is the following:
Create a program that
reads a single input character from the terminal
checks if the input character is a digit and, if so, converts it into the corresponding integer (use the property of the ASCII values above)
prints the value of the integer as an octal number (use the %o specifier in the argument of printf) or the text "the input is not a digit" if the user has entered a non-digit character, e.g. ‘q’, ‘$’ or ‘Z’.

My code is the following:

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

int valueOfDigit(){
    char c;
    int i;
    c = getchar();
    i = c;
    if (c <= '9' && c >= '1'){
        printf("%o", (int) i);
    }
    else printf("the input is not a digit\n");
    return 0;
}

Im failing the tests as i’m printing the ascii values and not octal. What am i doing wrong? We are not allowed to use any fancy methods either.

>Solution :

Your code does not work, because youre trying to print a char as an int(and by it i mean youre trying to print ‘6’ as 6). The problem is, that the chars are already ints in C(as youve noticed theyre encoded using ASCII standard). To do it simply, and by that i mean not checking anything related to program safety at all, you just have to do the following:

if (c <= '9' && c >= '0'){
        printf("%o", (int)(i - '0'));
    }

This will print the int number that corresponds to your number in ASCII minus ASCII zero number, which will result in actuall number being printed, for example 6 in ASCII is 54 so minus ‘0’ which is 48 you get 6. Thats the general idea.

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