用户输入断开while循环以返回主

时间:2015-05-15 01:13:45

标签: c codeblocks

所以,如果它是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");
}

1 个答案:

答案 0 :(得分:0)

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。

相关问题