My fscanf outputs a large negative number

五迷三道 提交于 2019-12-12 04:07:18

问题


In this program, I am attempting to read a name and their GPA from a file. The first name is Audrey, then a white space, and then 3.6. The second line is Oakley, then a white space, and 3.5.

int main()
{
    FILE * fPtr;
    FILE * fPtr2;

    char x[10] = { "Oakley " };
    double y;
    int z;

    fPtr = fopen("data.txt", "r");

    if (fPtr == NULL) // open failure
        puts("File open for read failed");
    else
    {
        while (scanf("%d", &z) != EOF)
        {
            fscanf(fPtr, "%s", x);
            fscanf(fPtr, "%lf", &y);
            fprintf(stdout, "Value read = %s\n", x);
            fprintf(stdout, "GPA = %lf \n", y);
        }
    }

    fclose(fPtr);
    system("pause");
    return 0;
}

So, I tried this once before and it worked. In that attempt, "x[10] = Audrey" and this was the first name in the list. It worked, and the fscanf gave me her GPA. The second time, I tried scanning for Oakley and I still get Audrey, but when I remove that line I get a really large negative number.

I used fscanf because it tokenizes around whitespace, so my theory is that if the cursor gets to the proper name then it will read the next number and that will be the GPA? Right? How do I get it to search for Oakley?


回答1:


You need check scanf for any errors, which could happen because the input file does not match the format you specified. Try these changes:

char user[100];

while (scanf("%s", user) == 1) {

    while (fscanf(fPtr, "%s %lf", x, &y) == 2)
    {
        if (strcmp(user, x) == 0) {
            fprintf(stdout, "GPA for %s is %lf \n", user, y);
            break;
        }
    }
    rewind(fPtr);
}

Also, fPtr2 is is uninitialized in your code, remove the line fclose(fPtr2).



来源:https://stackoverflow.com/questions/36904677/my-fscanf-outputs-a-large-negative-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!