gpt4 book ai didi

c - 如何将整数插入内存块?

转载 作者:行者123 更新时间:2023-11-30 18:10:18 25 4
gpt4 key购买 nike

有什么方法可以将整数放入已知大小的字符串中,如果可以,我该如何读取它?例如将 (int a=10) 转换为 (char string[200])。

最佳答案

Is there any way I can put an integer into a string of known size and if yes how can I read it? For example an (int a=10) into a (char string[200]).

是的,有使用printf的字符串版本

snprinf(string,200,"%d",a);

如果您想手动执行上述操作,也可以使用 div 和 mod by 10 循环生成字符串。 请参阅另一个答案以获取此示例 https://stackoverflow.com/a/49615617/391691

要从字符串中获取 int,可以使用 sscanfatoiatol

#include <stdio.h>
#include <stdlib.h>

void main(){
int a;
char string[200];


a = 10;
snprintf(string,200,"%d",a);
printf("As string:%s As int:%d\n",string,atoi(string));
}

我仍然不清楚这个问题的解释,与之前的答案相比,这代表了该问题的另一种解释 https://stackoverflow.com/a/58584291/391691

关于c - 如何将整数插入内存块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58584141/

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