在没有sprintf的情况下在C中将整数转换为字符串 [英] Converting integer to string in C without sprintf

查看:33
本文介绍了在没有sprintf的情况下在C中将整数转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没有sprintf可以在C中将整数转为字符串吗?

推荐答案

您可以在可用的情况下使用 itoa.如果它在您的平台上不可用,则可能会感兴趣以下实现:

You can use itoa where available. If it is not available on your platform, the following implementation may be of interest:

https://web.archive.org/web/20130722203238/https://www.student.cs.uwaterloo.ca/~cs350/common/os161-src-html/atoi_8c-source.html

用法:

char *numberAsString = itoa(integerValue); 

更新

根据 R.. 的评论,可能值得修改现有的 itoa 实现以接受来自调用者的结果缓冲区,而不是让 itoa 分配并返回一个缓冲区.

Based on the R..'s comments, it may be worth modifying an existing itoa implementation to accept a result buffer from the caller, rather than having itoa allocate and return a buffer.

这样的实现应该同时接受缓冲区和缓冲区的长度,注意不要超过调用者提供的缓冲区的末尾.

Such an implementation should accept both a buffer and the length of the buffer, taking care not to write past the end of the caller-provided buffer.

这篇关于在没有sprintf的情况下在C中将整数转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆