我编写了以下代码来编写文本。 strcmp 应该在用户键入 # 时终止文件写入。仍然没有这样做,我无法退出程序
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
char c[100];
fp = fopen ("/home/smksx/Desktop/uniprograms/domes/arxeio2","w");
printf ("\n\nWrite your text\n\n");
printf ("\n\nTerminate with #\n\n");
while (strcmp(c,"#")!=0)
{
scanf ("%s",&c);
if (strcmp(c,"#")!=0)
{
fprintf (fp,"%s",c);
}
}
fclose(fp);
return 0;
}
最佳答案
您的代码中有几个问题:
c 是指向 char 的指针,因此不能在 scanf 中使用 &
您的 while 循环正在 checkin 未初始化的数据
scanf 读取到\n,并且不将其添加到文件中
您的代码可能如下所示:
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
char c[100];
fp = fopen ("/home/smksx/Desktop/uniprograms/domes/arxeio2","w");
printf ("\n\nWrite your text\n\n");
printf ("\n\nTerminate with #\n\n");
while (1) // c is not initialized, so do not check it's content here
{
scanf ("%s",c); // c is pointer to char, so no & here
if (strcmp(c,"#")!=0) // here c is safe to be checked
{
fprintf (fp,"%s\n",c); // you may be adding a \n here
}
else
break; // do not repeat yourself: no need to double strcmp
}
fclose(fp);
return 0;
}
关于c - 使用 strcmp 终止文件写入不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60395798/