How to read an octal value using scanf in C

How to read an octal value using scanf in C:

Using scanf, we can read an octal value in C. In this post, I will show you how to do that with an example.

In octal number system, all numbers are defined by digits 0 to 7. For example, 8, 9 are octal numbers, but 10 is an octal number. So, octal numbers contains 0, 1, 2, 3, 4, 5, 6 or 7.

Reading octal values using scanf:

We can use %o format specifier in scanf to read octal values. Similarly, this format specifier can be used with printf to write octal numbers to console.

Example program:

Let’s take a look at the below program:

#include <stdio.h>
#include <ctype.h>

int main()
{
    unsigned int oct;

    printf("Enter a value in octal: ");
    scanf("%o", &oct);

    printf("You have entered: %o\n", oct);

    return 0;
}

Here, we have created one unsigned int variable to store the user input octal value. Using scanf, we are reading the octal value entered by the user and using printf, we are printing that value.

For both scanf and printf, it uses %o.

Sample output:

If you run this program, it will print output as like below:

Enter a value in octal: 123
You have entered: 123

Enter a value in octal: 129
You have entered: 12

Enter a value in octal: 99
You have entered: 0

For the second example, it reads 12, not 129, since 9 is not octal. For the third example, it prints the value as 0 as 99 is not octal.

You might also like: