0

I am wondering as to why when converting strings to int with either atoi or strtol it does not print the number 0 if its the first index, take this code for example

char s[] = "0929784";
long temp = strtol(s, NULL, 10);
printf("%li", temp);

OUTPUT: 929784

is there a way to have the 0 print?

Kevin H
  • 21
  • 3
  • 1
    uh, no ? Because 0929784 is not a number. Worst, in C, number beginning by 0 are octal base, so 0929784 is false. – Tom's Apr 16 '18 at 07:46
  • 2
    yes, printf("%s\n", s); muhaha – Serve Laurijssen Apr 16 '18 at 07:49
  • 1
    This doesn't have anything to do with strtol/atoi but everything to do with how you print the number. – Lundin Apr 16 '18 at 07:52
  • 1
    There definitely are dupes to this, but closing a C question as being a dupe to a C++question is a bad choice. – alk Apr 16 '18 at 08:02
  • 1
    I re-opened. Please don't use C++ posts for duplicates to C questions. String handling in particular is very different in the two languages. – Lundin Apr 16 '18 at 08:05

4 Answers4

3

Use

char s[] = "0929784";
size_t len = strlen(s);
long temp = strtol(s, NULL, 10);
printf("%0*li", (int) len, temp);

Details are here.

A more subtle and even safer approach would be:

char s[] = "0929784FooBarBlaBla"; 
char * endptr; 
long temp = strtol(s, &endptr, 10);
printf("%0*li", (int) (endptr - s), temp);

More details are here.

alk
  • 69,737
  • 10
  • 105
  • 255
2

printf will print the long in the best way possible, and that includes dropping any leading zeros.

For example, if someone asks you to write your age, you wouldn't write 028 if you were 28 would you? Even more sinister in C, a leading 0 denotes an octal constant, so actually 028 makes no sense as a number in C. Formally 0 is an octal constant although that, of course, doesn't matter.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • It makes sense, thank you for your help, I guess its just something I have to delve deeper into understanding. – Kevin H Apr 16 '18 at 07:51
1

An int basically stores leading zeros. The problem that you are running into is that you are not printing the leading zeros that are there. (source)

printf manual:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

So use:

printf("%0*li", (int) strlen(s), temp);
Abhishek Keshri
  • 3,074
  • 14
  • 31
0

Yes. Try

printf("%07li", temp);
MrPickles
  • 1,255
  • 1
  • 16
  • 31
  • 1
    It is a wrong approach because if the string does not contain a leading zero nevertheless it will be outputted due to formating. – Vlad from Moscow Apr 16 '18 at 07:48
  • 1
    @VladfromMoscow Then don't convert it to an integer. It sounds as if you don't want a number. You want a string apparently. – Zan Lynx Apr 16 '18 at 07:49