atoi 和十进制数前导 0
在 CI 中使用atoi时,我尝试将数字的char
数组转换为int
。不过,我的号码上有前导 0
,当我稍后打印号码时,它们不会被保留。
char num[] = "00905607";
int number;
number = atoi(num);
printf("%d", number);
其输出将是 905607
,我希望它是 00905607
。
有什么想法吗?
When using atoi
in C I am trying to convert a char
array of numbers to an int
. I have leading 0
's on my number though and they are not preserved when I print the number out later.
char num[] = "00905607";
int number;
number = atoi(num);
printf("%d", number);
The output from this will be 905607
and I would like it to be 00905607
.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
您可以在 printf() 上进行填充,因此如果您希望每个输出都是 8 个字符长,您可以使用
You can do padding on your printf() so if you wanted every output to be 8 characters long you would use
请改用 strtol 。它允许您指定基础。
Use strtol instead. It allows you to specify the base.
该代码如果能正常工作的话,就可以正常工作。整数是 905607...前导零在数学意义上不存在。
该代码有很多问题。您声明的字符串不正确,并且没有打印转换后的数字。另外,如果您正在执行
printf(number);
您需要使用格式字符串。如果您希望其中有前导空格,可以使用宽度说明符。That code is working properly, if it works at all. The integer is 905607... leading zeros don't exist in a mathematical sense.
You have a lot of issues with that code. You're declaring your string improperly, and you're not printing the converted number. Also, if you were doing
printf(number);
you'd need to use a format string. If you'd like to have leading spaces in that, you can use a width specifier.不要使用阿托伊。使用以 10 为底的 strtol。
一般来说,没有理由在以下情况中使用 atoi
现代代码。
Don't use atoi. Use strtol with a base of 10.
In general, there's no reason to use atoi in
modern code.
大多数答案假设您需要 8 位数字,但这并不完全是您所要求的。
如果您想保留前导零的数量,最好将其保留为字符串,并使用
strtol
进行转换以进行计算。Most answers assume you want 8 digits while this is not exactly what you requested.
If you want to keep the number of leading zeros, you're probably better keeping it as a string, and convert it with
strtol
for calculations.是的,当你想显示整数时,你必须再次将它们格式化为字符串。整数只是一个数字,它不包含任何有关如何显示它的信息。幸运的是, printf 函数已经包含了这个,所以就像这样
Yes, when you want to display ints you have to format them as strings again. An integer is just a number, it doesn't contain any information on how to display it. Luckily, the printf-function already contains this, so that would be something like
您可以使用 sscanf,并提供“%d”作为格式字符串。
You could use sscanf, and provide '%d' as your format string.
如果你不想要这种行为;不要使用atoi。
也许 sscanf 具有 %d 格式?
If you don't want that behavior; don't use atoi.
Perhaps sscanf with a %d format?
您还可以计算字符串中数字的数量,并创建一个带有前导零的新数字。
或者查看 printf 的所有精彩格式标签,并使用 1 来填充零。
例如,这里有很多:
http://www.cplusplus.com/reference/clibrary/cstdio/printf/
You could also count the numbers of numbers in the string and create a new one with leading zeroes.
Or check out all the wonderful format tags for printf and use one to pad with zeroes.
Here for example are lot of them:
http://www.cplusplus.com/reference/clibrary/cstdio/printf/