为何atoi/strtol转换首字符为0的字符串为整数时不保留前导0?
Great question! Let's break this down step by step.
为什么前导0会消失?
The short answer is that integer types like long or int don't store leading zeros at all. Leading zeros in a string are just a formatting detail—they don't change the actual numeric value of the number. When you use strtol() or atoi(), you're converting the string representation of a number into its raw numeric value, which discards any formatting (like leading zeros) that doesn't affect the value itself. So "0929784" and "929784" both resolve to the same numeric value: 929784.
如何让输出保留前导0?
Since the integer itself doesn't track leading zeros, you need to preserve that formatting information before converting the string to an integer. Here are two reliable approaches:
Use printf's format specifiers to pad with zeros
You can leverageprintf()'s formatting capabilities to dynamically add leading zeros to match the original string's length. First, grab the input string's length withstrlen(), then use the%0*lispecifier to pad the output to that length:#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char s[] = "0929784"; int original_len = strlen(s); long temp = strtol(s, NULL, 10); // %0*li = pad with zeros to the width specified by original_len printf("%0*li\n", original_len, temp); return 0; }This will output
0929784, matching the original string's formatting exactly.Directly output the original string (if applicable)
If you don't need to perform any numeric operations on the value (like arithmetic), you can skip the conversion entirely and print the string directly:char s[] = "0929784"; printf("%s\n", s);This works best if your input is guaranteed to be a valid numeric string with no non-digit characters. If you do need to process the number first, stick with the first approach.
A quick side note: Since you're using strtol(s, NULL, 10), the leading zero doesn't trigger octal parsing (that only happens when the base argument is 0). So your conversion to 929784 is totally correct—no issues with invalid octal values here.
内容的提问来源于stack exchange,提问作者Kevin H

