c - 使用 strcmp 终止文件写入不起作用

标签 c file strcmp

我编写了以下代码来编写文本。 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;
}

最佳答案

您的代码中有几个问题:

  1. c 是指向 char 的指针,因此不能在 scanf 中使用 &

  2. 您的 while 循环正在 checkin 未初始化的数据

  3. 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/

相关文章:

C -错误 : expected ';' , ',' 或 ')' token 之前的 '='

android - 我在 android 中的应用程序文件夹在哪里?

java - Android studio,打开一个文件,不断写入然后关闭

c - 我怎样才能比较两个字符串不止一个字符?

c - 分割。 strcmp [C]

c - 在 C 中使用 strcmp() 函数

c - 纯C语言截取桌面截图的程序

c - C 中的文件处理和函数

cocoa - 如何将 NSImage 保存为新文件

c - 在 Windows CLion 中显示静态 ASCII 数据(如诅咒)?