用户输入中断 while 循环到 return 到 main

User input to break while loop to return to the main

所以,如果它是 C,我需要用用户输入来打破循环,但它不会打破循环,return 到 main。

它坚持同一个循环。

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 是一个标准库函数,它比较两个字符串(给定指向它们各自初始字符的指针)和 returns 如果第一个出现在第一位(按字母顺序),则为负整数,如果为正如果第二个在前,则为整数;如果两个字符串相等,则为 0。