无法读取我的书面文件(C编程学生数据库)

时间:2016-03-02 09:23:53

标签: c

我们得到了一个程序来制作一个程序来阅读我们的文本文件中写的内容(姓名,学号,课程,年份,部分等等)。但我似乎无法做到工作,你能告诉我什么是错的吗?

y = 0

This是我的文本文件中的内容。

输入文件的前几行:

#include <windows.h>
#include <conio.h>
#include <stdio.h>

struct record
{
       char name[50],number[50],course[50],gender;
       int year, section;
       float midterm,final,average,sum;
};

int main()
{
    int a=1,n;
    int passed=0,failed=0;

    FILE *fp;
    fp = fopen("BSU.txt","r");

    if(fp==NULL)
    {
           printf("ERROR!");
           getch();
    }

    struct record student[25];

    printf("Please input the number of students: ");
    scanf("%d", &n);

    for(a=0;a<n;a++)
    {
          fscanf(fp, "%f", student[a].average);// I CANNOT MAKE THE FSCANF WORK!!//
    }

    getch();        
}

3 个答案:

答案 0 :(得分:2)

应该是

fscanf(fp, "%f", &student[a].average);

而不是

fscanf(fp, "%f", student[a].average);

但是这允许您只读取包含数字的文件,例如:

1.5
1.9
2.7

您想要阅读的文件更加复杂。

因此,在for循环中,您需要阅读10行,从每行中提取相关信息,将该信息存储在记录的相应字段中,并将记录存储在某处。

答案 1 :(得分:1)

You need to consider the input file format. When you're calling fscanf the 'cursor' is located at the first line of your file. What you need to to is to bring the cursor to the line you want to read.

Student Name: Mark Benedict D. Lutab <-- cursor is located at the beginning of this line 
Gender: M
Student Number: 2015-04711-MN-0
Course: BSIT
Year: 1
Section: 2
Midterm Grade: 2.00
Final Grade: 1.75
Average Grade: 1.8 <-- you need the cursor here

To achieve that you can use fgets in an while loop to get rid of the lines before the desired line.

char line[256];
while( fgets(line, 256, fp) && line[0] != 'A'); // line[0] != 'A' makes the loop stop when it reached the desired line

Now your cursor is at the desired line, however you need to get rid of the text in front of the value you want to read.

Average Grade: 1.8 <-- get rid of "Average Grade: "

The good thing is line already contains this line, so you can use sscanf to read formatted from this string.

sscanf(line, "%*s %*s %f", &student[0].average); // note the ampersand in front of student[0].average to get its address

Using %*s makes sscanf ignore the words "Average" and "Grades:" so %f will read the desired value.

答案 2 :(得分:0)

因为它看起来像你的作业,我不会给你解决方案,但我告诉你哪里有bug。

您使用fscanf的方式不正确。这一行:

fscanf(fp, "%f", &student[a].average);

讲的是:“取一些值(浮动类型)并将其写入学生[a] .average”。 它无法在您的情况下工作,因为您的数据结构更加复杂。

你有什么要做的? 首先,尝试在输出中写入文件中的所有数据。 之后,您应该尝试解析您感兴趣的行:)

了解getline,sscanf。这对你很有帮助:))