读取文本文件并比较每一行

时间:2015-12-03 19:20:36

标签: c variable-assignment

我的作业有一个txt文件。我必须扫描第一行并将其与其他行进行比较

(
BACCDEABCEEDCDABBAED
6734 BXCCDAABCEEDCDACBAED
7843 BADCXAABCEXXCDABBAED
2223 BCBAEACCDAEDCDABBAEA
2324 BACXDEABCEEDCDAABAED
3474 BACCDEABCEEDCDABBAED
3434 XADCDAABCEEDCDABBAED
6374 XXXXXCXXXXXXXXXXXAED
3332 BADCDEABCEEDCDADBCEX
3454 BACCXEABCEEDCXABBAED
0
)

我如何将第一个数字分开并将[20](Correct_ answers)其他字母与第一行20进行比较?

这是我到目前为止所得到的.........

#include <stdio.h>
#include <stdlib.h>

int main(){
    char answer[20];

    char studentAnswer[20];

    int studentId[4];

    int x;

    int correct=0,wrong=0,notAttempted=0;

    FILE * in = fopen("/Users/MarkB/Desktop/ASSIGNMENT3/exam.txt", "r");
    FILE * out = fopen("/Users/MarkB/Desktop/ASSIGNMENT3/examRsults.txt", "w");

    fscanf(in,"%d",studentId);
    fscanf(in,"%s",answer);
    fscanf(in,"%s",studentAnswer);
    while (studentId !=0){
        for (x=0; x<20;x=x+1){
            if(answer[x]==studentAnswer[x]){
                correct=correct + 1;
            }
            if(answer[x]!=studentAnswer[x] && studentAnswer[x]!='X'){
                wrong=wrong + 1;
            }
            if(studentAnswer[x]=='X'){
                notAttempted=notAttempted + 1;
            }
        }
    }

    fprintf(out,"--------Student Exam results------\n");

    fprintf (out,"%d",studentId[0]);



    fprintf (out,"Questions Correct: %d \n",correct);
    fprintf (out,"Questions Wrong: %d \n",wrong);
    fprintf (out,"Questions not attempted: %d \n",notAttempted);

    system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:1)

您的代码

fscanf(in,"%s",studentAnswer);

未考虑学生答案前的身份证明。如果输入文件确实包含'('和')',那么您还必须考虑跳过它们。你还必须以某种方式比较你所在行的id。你必须比较你在while循环中得到的id,直到你能读出学生的答案。