gpt4 book ai didi

c - 程序不工作

转载 作者:太空宇宙 更新时间:2023-11-04 05:50:45 25 4
gpt4 key购买 nike

我仍然被认为是 c 的初学者,我开始学习文件。我已经建立了一个空白文件。每次我编译这个程序时,文件仍然是空白的。需要帮助!!

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

int main()
{
FILE * x;
char name[25];

printf("enter your name: ");
scanf("%s", &name);

x = fopen("x1.txt", "w");

if(x = NULL)
{
printf("Unable to open the file");
}

else
{
fprintf(x, "%s\n", name);

printf("date has been entered successfully to the file");
fclose(x);
}


return 0;
}

谢谢

最佳答案

在进行以下更改并重建/运行程序后,存在一个文件,其中包含我的名字:

(原因见行内评论)
变化:

if(x = NULL)//assignment - as is, this statement will always evaluate 
//to false, as x is assigned to NULL.

收件人:

if(x == NULL)// comparison - this will test whether x is equal to NULL without changing x.

更改:(这是您的文件未被填充的关键)

   scanf("%s", &name);//the 'address of' operator: '&' is not needed here.
//The symbol 'name' is an array of char, and is
//located at the address of the first element of the array.

收件人:

   scanf("%s", name);//with '&' removed.

或者更好:

   scanf("%24s", name);//'24' will prevent buffer overflows
//and guarantee room for NULL termination.

还有一种方法可以解决关于 的评论 not using scanf at all... :

char buffer[25];//create an additional buffer
...
memset(name, 0, 25);//useful in loops (when used) to ensure clean buffers
memset(buffer, 0, 25);
fgets(buffer, 24, stdin);//replace scanf with fgets...
sscanf(buffer, "%24s", name);//..., then analyze input using sscanf
//and its expansive list of format specifiers
//to handle a wide variety of user input.
//In this example, '24' is used to guard
//against buffer overflow.

关于最后一种方法,这里是一个页面 detailing the versatility 使用 sscanf 处理用户输入的字符串。

关于c - 程序不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42866761/

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