【问题标题】:why is my function not working properly when i call for it?为什么我的功能在我调用它时不能正常工作?
【发布时间】:2021-02-01 22:28:51
【问题描述】:

我已经写了下面的代码

void readfile();

struct profile {
    char name[30];
    int age, phoneNo;
};

int main()
{
    FILE* fPtr;
    fPtr = fopen("profile.txt", "a");

    printf("\n\nPlease enter your details:");
    struct profile c;
    printf("\n\nEnter your name: ");
    gets(c.name);
    printf("\nEnter your age: ");
    scanf("%d", &c.age);
    printf("\nEnter your phone number: ");
    scanf("%d", &c.phoneNo);

    fprintf(fPtr, "%s,%dy,%d#\n", c.name, c.age, c.phoneNo);

    fclose(fPtr);

    readfile();

    return 0;
}

上面的代码接受来自用户的数据并放入一个名为 profile.txt 的文本文件中,文本文件中存储的记录如下所示:

James Brown,37y,01123456789#
Mary Ann,45y,0123456749#

我在主程序中调用了函数readfile();,但该函数不能正常工作。 readfile();的代码如下:

void readfile()
{
    char fName[15], line[30];

    FILE *f;
    f = fopen("profile.txt", "r+");

    printf("Enter name: ");
    fgets(fName, sizeof(fName), stdin);

    while (fgets(line, sizeof(line), f)) {
        fName[strcspn(fName, "\n")] = '\0';
        if (strstr(line, fName) != NULL) {
            printf("%s", line);
        }
    }

    fclose(f);
}

在这个函数中,我想搜索一个名字并打印出包含记录的整个字符串。但是当我执行我的代码时,代码fgets(fName, sizeof(fName), stdin); 似乎被忽略了,因为它不允许我输入要搜索的名称。相反,它只是打印出文件内容的ALL,这违背了目的。当我使用没有其他代码的main() 调用此函数时,它工作得很好,所以我不确定为什么当我的main() 中有代码时,该函数会停止正常工作?如果有人能指出我如何在我的代码中解决这个问题,我将不胜感激。

【问题讨论】:

    标签: c function while-loop main fgets


    【解决方案1】:

    你正在使用return 0作为void readfile()函数,删除return 0

    我刚刚发布了您上一个问题的答案,请参考。

    search string from file and store it in struct using c

    【讨论】:

    • 您好,感谢您回答我之前的问题。 :) 对于这个问题,我在我的 void 函数中删除了 return 0,但它仍在打印所有数据。我认为问题出在我的主要功能上。
    • 在您的主函数中,您以附加模式fPtr = fopen("profile.txt", "a"); 打开文件,如果您多次运行程序(检查一次profile.txt),那么相同的条目将附加在文件末尾profile.txt,更好用fPtr = fopen("profile.txt", "w");
    猜你喜欢
    • 1970-01-01
    • 2022-01-05
    • 2021-12-09
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多