提问人:Webbo 提问时间:8/14/2020 最后编辑:Webbo 更新时间:8/14/2020 访问量:618
在 c++ 中仅使用“char”比较两个输入文件
Comparing two input files using only "char" in c++
问:
我正在寻找一些关于作业问题的帮助,或者更多的是朝着正确的方向推动。我们不允许使用字符串。我们确实需要使用 eof。
问题:
评估多项选择题考试需要两个数据文件。第一个文件 (小册子.dat)包含正确答案。问题总数为 50 个。一个 示例文件如下: ACBAADDBCBDDAACDBACCABDCABCCBDDABCACABABABCBDBAABD
第二个文件(answer.dat)包含学生的答案。每行有一个 包含以下信息的学生记录: 学生的答案(共50个答案):每个答案可以是A、B、C、D 或 *(表示无答案)。
答案之间没有空白。 学生证 学生姓名 下面给出了一个示例文件: AACCBDBCDBCBDAAABDBCBDBAABCBDDBABDBCDAABDCBDBDA 6555 马赫穆特 CBBDBCBDBDBDBABABABBBBBBBBBBBBBDBBBCBBDBABBBDC** 6448 新南 ACBADDBCBDDAACDBACCABDCABCCBDDABCACABABABCBDBAABD 6559 CAGIL
编写一个 C++ 程序来计算每个学生正确答案的总数 并将此信息输出到另一个名为 report.dat 的文件。
对于上面给出的示例文件,输出应如下所示:
6555 马赫穆特 10
6448 新南 12
6550 卡吉尔 49
请参阅下面的问题和我的代码。我认为最好将学生的答案放入 2d 数组中,但每次我尝试这样做时,我都没有得到正确的输出。任何帮助将不胜感激。
#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;
}
答:
我不太明白你为什么要将答案存储在一个数组中。你能不能做这样的事情:
while( fileHasNotEnded )
{
answers >> answerOfStudent;
memo >> correctAnswer;
if( AnswerOfStudent == correctAnswer )
correctAnswerCounter++;
}
评论
这是实现目标的一种方法,还有很多其他方法。
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;
}
}
在上面的代码中,读取并存储答案密钥。
对于每个学生行,都会读入学生的答案,然后与答案键进行比较。内部循环计算正确答案的数量。
比较答案后,将打印数据行的剩余部分,直到行的末尾。当遇到行尾时,将打印正确的答案数量。
评论
char