如何在C中将int转换为字符串? [英] How to convert an int to string in C?

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

问题描述

如何将int(整数)转换为字符串?我正在尝试创建一个将struct的数据转换为字符串以将其保存在文件中的函数.

How do you convert an int (integer) to a string? I'm trying to make a function that converts the data of a struct into a string to save it in a file.

推荐答案

编辑:正如注释中指出的那样,itoa()不是标准,因此最好使用sprintf()方法.竞争的答案!

As pointed out in the comment, itoa() is not a standard, so better use sprintf() approach suggested in the rivaling answer!

您可以使用itoa()函数将您的整数值转换为字符串.

You can use itoa() function to convert your integer value to a string.

这里是一个例子:

int num = 321;
char snum[5];

// convert 123 to string [buf]
itoa(num, snum, 10);

// print our string
printf("%s\n", snum);


如果要将结构输出到文件中,则无需事先转换任何值.您可以只使用 printf格式规范来指示如何输出值和使用 printf系列中的任何运算符来输出数据.


If you want to output your structure into a file there is no need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.

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

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