I am using C to read integer data using scanf("%i", &myInt)
. I know for this particular input the data will ALWAYS be three digits. However, sometimes I need to read a number with leading 0's like 001 or 078. When scanf()
reads a number with a leading zero it will not pick up the subsequent digits. For example, when I read 078 scanf
reads 7 then the next scanf
will read the 8. I would like scanf
to read 78. Can someone tell me how to do this properly? Here is a code example:
int x;
while (scanf("%i", &x) != EOF) {
//do operations on each of the digits
}
You can add leading zeros to an integer by using the "D" standard numeric format string with a precision specifier. You can add leading zeros to both integer and floating-point numbers by using a custom numeric format string. This article shows how to use both methods to pad a number with leading zeros.
Step 1: Get the Number N and number of leading zeros P. Step 2: Convert the number to string using the ToString() method and to pad the string use the formatted string argument “0000” for P= 4. val = N. ToString("0000");
So we use “%[^\n]s” instead of “%s”. So to get a line of input with space we can go with scanf(“%[^\n]s”,str);
The “%d” in scanf allows the function to recognise user input as being of an integer data type, which matches the data type of our variable number. The ampersand (&) allows us to pass the address of variable number which is the place in memory where we store the information that scanf read.
I suspect you may be using the %i
conversion specifier which honors C conventions like 0x
denoting hex, and leading zeros denoting octal. If the input is 078
and %i
is used, then only 07
matches because 8
is not an octal digit. Use %d
to scan decimal integers.
The i
in %i
does not mean "reach for me whenever you need to convert an i)nteger to type i)nt".
The width is only necessary if the three digit number is followed by more digits which we need to exclude from the scan. For instance, we can convert a date given as "20140417"
into three integers using the format string "%4d%2d%d"
. The last %d
could be %2d
but doesn't have to be. These values do not specify how many digits to extract, but rather they specify a maximum field width: the conversion takes up to that many characters (including a possible plus or minus sign). For the input -1234
, the %3d
conversion will take -12
, and leave the 34
. For the input 1$
, %3d
will just take the 1
and leave the $
, because it isn't a decimal digit.
You can use a width delimiter with scanf, even on integer types :
int i;
scanf ("%3d",&i); // Will read 3 characters and interpret them as an integer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With