首页 > 解决方案 > 在对 fgets 的不相关函数调用后清除字符数组?

问题描述

我正在为 C 中的一个项目创建一个文件管理程序,我遇到了这个错误,这对大多数程序员来说可能很明显,但由于我真的很糟糕,我无法发现我做错了什么。我的主程序是一个界面,它向用户询问文件名并将其分配给数组fileName

int main() {
    char fileName[50];
    assignFileName(fileName);
    char option[2];
    int checkInput;
    do {
        printf("File management program. Options :\n '1' for File operations (Create, copy, delete or display file)\n '2' for Line operations (Append, delete, display or insert line to file)\n '3' for General operations (Display change log or number of lines for file)\n '4' to select a new file\n '9' to exit program\n");
        printf("aaa %s\n", fileName); //first printf check - prints "aaa" and value in fileName
        checkInput = checkUserInput(option);
        printf("aaa %s\n", fileName); // second printf check = prints only "aaa"
        if (checkInput == 1) {
          //... etc
        }
void assignFileName(char *fileName) {
    printf("Enter file name to operate on, or 'E' to exit the program.\n");
    do {
        if ((fgets(fileName, 50, stdin)) != NULL) {
            if (fileName[strlen(fileName)-1] = '\n') {
                fileName[strlen(fileName)-1] = '\0'; 
            }
            if (strlen(fileName) == 1 && *fileName == 'E') {
                exit(0);
            } else if (strlen(fileName) == 0) {
                printf("Error : Please enter a file name or 'E' to exit.\n");
            }
        } else {
            perror("Error assigning file name ");
        }
        
    } while (strlen(fileName) == 0);
}

我很确定这段代码没问题。可能有很多方法可以提高效率,如果有人想提供他们的意见,我会考虑的。但是,问题出现在代码的后面。我有 2 个 printf 语句来检查文件名的值。在第一个之后,一切似乎都很好,但是对于第二个,fileName 的值似乎被清除了,所以 checkUserInput 中显然发生了一些事情。所有 checkUserInput 所做的就是检查用户输入一个数字:

void flush() {
    int ch;
    while ((ch = getchar()) != '\n' && ch != EOF) {
    }
}

int checkUserInput(char *input) {
    if (fgets(input, 3, stdin) != NULL) {
        printf("you entered %c\n", input[0]);
        if (input[1] == '\n') {
            return 1;
        } else {
            flush();
            printf("Error : Please enter one of the options given.\n");
        }
    } else {
        printf("Error : Please try again.\n");
    }
    return 0; 
}

我将更多 printf 语句用于错误检查,似乎在调用 fgets(input, 3, stdin) 后,fileName 中的值被清除了。谁能向我解释为什么会这样?我什至没有将数组文件名传递给 checkUserInput,所以我什至不知道程序是如何改变它的。这是控制台显示内容的链接:(无法发布图片,抱歉,不是 10 个代表)。 https://cdn.discordapp.com/attachments/708320229737889832/802557193043050516/unknown.png

所有帮助将不胜感激。谢谢。

标签: cfgets

解决方案


if (fileName[strlen(fileName)-1] = '\n')应该:

if (fileName[strlen(fileName)-1] == '\n') 

请注意,您可以使用以下简单行去除尾随换行符:

filename[strcspn(filename, "\n")] = '\0';

推荐阅读