因此,如果它是C,我需要用用户输入来中断循环,但是它不会中断循环并返回到主循环。

它坚持相同的循环。

void createFile(void)
{
    FILE *NewFile;
    char *file_name = malloc(sizeof(*file_name));
    printf("\nEnter a name of the file you want to create:\n");
    scanf("%s",file_name);

    while(access(file_name, 0) != -1)//in case the file exists
        {
        printf("\n%s file already exists\nplease re_enter your file name or C to go back to the main menu.\n\n", file_name);
        scanf("%s", file_name);
        if ( file_name == 'C')
        {
            return;// returning to the main menu
        }
        }
    if(access(file_name, 0) == -1)//if it does not exist
    {
        NewFile = fopen(file_name,"w+");
        fclose(NewFile);
        printf("\nFile has been created successfully! :D\n\nPlease enter R to return to the main menu ");
        scanf("%s",file_name);
        if (file_name == 'R')
        {
            return;
        }
    }
    remove("C"); // just in case unwanted C file is created.
    remove("R");
}

最佳答案

file_name是指向字符的指针。 (实际上,它是一个以NUL终止的字符序列的第一个字符的指针,但仍然是一个字符的指针。)从声明中可以明显看出:

char *file_name;


另一方面,'C'是整数。最有可能的是整数67,它是字母C的ASCII码。

因此,您正在将指针(即地址)与整数进行比较。

在C语言中,这实际上是合法的,但是只有当您与之比较的整数为0时,它才有意义。因此,编译器应对此发出警告。

最终结果是比较file_name == 'C'评估为0(假)。

您打算做的是将file_name指向的字符串与字符串文字"C"进行比较,您将执行以下操作:

if (strcmp(file_name, "C") == 0))


strcmp是一个标准的库函数,它比较两个字符串(给定指向它们各自初始字符的指针),如果第一个字符串(字母顺序)排在第一位,则返回负整数;如果第二个字符串排在第一位,则返回正整数;如果第二个字符串在第一位,则返回0。这两个字符串相等。

09-10 01:28
查看更多