在C ++中仅使用“ char”比较两个输入文件

问题描述

我正在寻找有关分配问题的帮助,或者只是朝着正确的方向轻推。我们不允许使用字符串。我们确实需要使用eof。

问题:

需要两个数据文件来评估多项选择检查。第一个档案 (booklet.dat)包含正确的答案。问题总数为50。A 示例文件如下: ACBAADDBCBDDAACDBACCABDCABCCBDDABCACABABABCBDBAABD

第二个文件(answer.dat)包含学生的答案。每行有一个 学生记录,其中包含以下信息: 学生的答案(共50个答案):每个答案可以是A,B,C,D 或*(代表没有答案)。

答案之间没有空白。 学生卡 学生姓名 示例文件如下: AACCBDBC DBCBDAAABDBCBDBAA BCBDD BABDBCDAABDCBDBDA 6555 MAHMUT CBBDBC BDBDBDBABAABABABBBBBABBABBBBD BBBCBBDBABBBDC ** 6448 SINAN ACB ADDBCBDDAACDBACCABDCABCCBDDABCACABABABCBDBAABD 6559 CAGIL

编写一个C ++程序,计算每个学生正确答案的总数 并将此信息输出到另一个名为report.dat的文件。

对于上面给出的示例文件,输出应如下:

6555 MAHMUT 10

6448泗南12

6550 CAGIL 49

请在下面查看问题和我的代码。我认为最好将学生的答案放入二维数组中,但是每次尝试时,都不会获得正确的输出。任何帮助将不胜感激。

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std; 


int main(){

char answerKey[50];
char studentDetails;
char studentAnswers[3][50];
char next;
ifstream memo,answers;

memo.open("booklet.dat");
if (memo.fail()){
    cout << "booklet.dat failed to open. \n";
    exit(1);
}

answers.open("answer.dat");
if (memo.fail()){
    cout << "answer.dat failed to open. \n";
    exit(1);
}

for (int i = 0; i < 50; i++){
    memo >> next;
    answerKey[i] = next;
    }

for (int i = 0; (next != '\n'); i++){
    for (int j = 0; j < 50; j++){
        answers >> next;
        studentAnswers[i][j] = next;
    }
}

return 0;
}

解决方法

这是实现目标的一种方法,还有许多其他方法。

const unsigned int  MAX_ANSWERS = 50U;
char answer_key[MAX_ANSWERS] = {0};

// Read in the answer key.
std::ifstream answer_file("booklet.dat");
answer_file.read(&answer_key[0],MAX_ANSWERS);

// Process the students answers
char student_answers[MAX_ANSWERS] = {0};
std::ifstream student_file("answer.dat");
while (student_file.read(&student_answers[0],MAX_ANSWERS))
{
    correct_answers = 0;
    for (unsigned int i = 0; i < [MAX_ANSWERS]; ++i)
    {
        if (student_answers[i] == answer_key[i])
        {
            ++correct_answers;
        }
    }
    // Output the remainder of the line.
    char c;
    while (student_file >> c)
    {
        if (c == '\r')  continue; // Don't print the CR
        if (c == '\n')
        {
             cout << correct_answers;
             cout << endl;
             student_file.ignore(10000,'\n');
             break;
        }
        cout << c;
    }
}

在上面的代码中,读取并存储了答案键。

对于每个学生行,将读取学生的答案,然后将其与答案键进行比较。内部循环计算正确答案的数量。

比较答案后,将打印数据行的其余部分,直到该行的末尾。当遇到行尾时,将打印正确的答案数量。

,

我不太明白为什么要将答案存储在数组中。您能不能做这样的事情?

while( fileHasNotEnded )
{
    answers >> answerOfStudent;
    memo >> correctAnswer;
    if( AnswerOfStudent == correctAnswer )
        correctAnswerCounter++;
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...