gpt4 book ai didi

c - fprintf 将垃圾打印到 txt 文件

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

我在使用字符串和 c 时遇到问题。

我正在尝试做一些非常简单的事情:将 int 转换为字符串并按以下方式将其打印到 txt 文件中。

const char * test_string() {
char s[5];
int num = 123;
sprintf(s, "%d", num);
return s;
}

int save() {
FILE *fh = fopen("test.txt", "w");
const char * text = test_string();
fprintf(fh, "%s", text);
fclose(fh);
}

但是,对于这个简单的任务,我得到了以下结果:

Üþ(

我需要一些帮助来解决这个问题。提前致谢。

最佳答案

stest_string 中的局部变量,因此当 test_string 返回时它会被销毁。然后,您尝试打印不再存在的变量的值。

关于c - fprintf 将垃圾打印到 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39735289/

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