我的fscanf输出较大的负号 [英] My fscanf outputs a large negative number

查看:175
本文介绍了我的fscanf输出较大的负号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个程序中,我试图读取名称和文件的GPA。第一个名字是贝贝,然后空格,然后3.6。
第二行是奥克利,则一个空格和3.5。

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;
}

所以,我曾经尝试过这一点,它的工作。在该尝试中,×[10] =奥黛丽,这是在该列表中的第一个名称。它的工作,和的fscanf给了我她的GPA。第二次,我试图扫描奥克利和我仍然得到奥黛丽,但是当我删除了这一行,我得到一个真正的大负数。

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.

我用的fscanf因为它tokenizes周围的空白,所以我的理论是,如果光标到达正确的名字,那么它会读取下一个号码,这将是GPA?对?我如何得到它来搜索奥克利?

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?

推荐答案

您需要检查 scanf函数的任何错误,这可能发生,因为输入文件不匹配的格式您指定。试试这些变化:

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);
}

此外, fPtr2 是未初始化在code,删除行 FCLOSE(fPtr2)

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

这篇关于我的fscanf输出较大的负号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆