1

I was trying to print a integer in c but those starting with zeroes causing me problem. For example if no. is 01234 it is printing like 1234 instead of 01234.please tell how to do it in C

My problem is that there are 2 integers and I want to know whether first integer is in the starting of second or not.

for ex- 123 and
12345 "yes" because 123(first integer) is in the beginning of second integer(12345)

but in case 123 and
012345 it should print "no" because 123 in not in the beginnig of 0123345 but in c trailing zeroes get deleted and my program is printing "yes"

please tell what to do (note-no.of digits can vary in range of integer and 2nd integer is either equal or greater then 1st integer)

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
himanshu
  • 39
  • 1
  • 7

3 Answers3

4
int i = 1234;
printf("%08d", i);   // zero-pad to 8 places.
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
1

my suggestion would be , If you are taking the value from STDIN from the user. Then if you want to use that value for printing purpose, then you need to store that integer with leading zeros into a string rather than an integer. Because leading zero has no meaning if you are storing that string value in an integer.

so %s in printf with retain the number of zeroes that user has enetered in that way.

Vijay
  • 65,327
  • 90
  • 227
  • 319
0
#include <stdio.h>
#include <string.h>

#define N_DIGITS 64

main()
{
    char a[N_DIGITS], b[N_DIGITS];
    scanf("%s%s", a, b);
    if(strncmp(a, b, strlen(a))==0)
        puts("yes");
    else
        puts("no");
    return 0;
}

Note that the length of digits is limited by value N_DIGITS. The result is as below;

$ ./a.out <<<"123 12345"
yes
$ ./a.out <<<"123 012345"
no
kamae
  • 1,825
  • 1
  • 16
  • 21