gpt4 book ai didi

c - 如何将随机数存储到以 null 结尾的字符数组中?

转载 作者:太空宇宙 更新时间:2023-11-04 02:11:46 24 4
gpt4 key购买 nike

我认为使用 fgets 是最好的选择,但显然它需要从标准输入输入?如何使用 rand() 生成随机数并存储它?

最佳答案

你可以使用sprintf():

char buf[11];
int r = rand();
sprintf(buf, "%d", r);

如果您的运行时库提供了 snprintf(),一个更稳健的选择是:

snprintf(buf, sizeof(buf), "%d", r);

以这种方式使用 snprintf() 可确保生成的字符串不会溢出 buf 的边界。

关于c - 如何将随机数存储到以 null 结尾的字符数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13148699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com