我有一个家庭作业计划,我需要一些帮助。我需要将包含测试答案键的数组与包含学生答案的数组进行比较。我遇到的问题是我需要考虑空白的答案。我似乎无法提出将比较数组的代码,然后显示分数。对于正确答案,测试评分为2分,对于错误答案,评分为1分,对于空白答案,评分为零分。
这是输入的一个例子:
TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF
第一行是键,第二行是学生数据的第一行。
这是我的代码:
#include <cmath>
#include <fstream>
#include <cstring>
#include <string>
#include <iostream>
using namespace std;
int checkAnswers(char key[], char answers[]);
void displayGrade(int score);
int main()
{
ifstream inFile;
int score = 0;
char key[21];
string studentID;
char answers[21];
int studentCount;
inFile.open("Ch9_Ex6Data.txt"); //opens input file
if (!inFile) //sets condition for if input file does not exist
{
cout << "Unable to locate file." << endl; //informs user that input file is missing
cout << "Program terminating." << endl; //informs user that program is terminating
return 1; //terminates program with error
}
inFile.getline(key, 21);
cout << "Processing Data..." << endl << endl;
cout << "Key: " << key << endl << endl;
while (inFile >> studentID)
{
cout << studentID;
inFile.getline(answers, 22);
cout << answers << " ";
score = checkAnswers(key, answers); //calls checkAnswer function and sets result equal to score
displayGrade(score);
}
return 0;
}
//User-defined Function 1
int checkAnswers(char key[], char answers[])
{
//Function Variables
int i, length; //declares i variable
int correct = 0, incorrect = 0, blank = 0, score = 0; //declares and initializes correct, incorrect, blank, and score variables
answers >> length;
for (i = 0; i < 22; i++) //initiates conditions for for loop
{
if (answers[i] == ' ') //initiates if condition
{
i++;
}
else if (key[i] == answers[i]) //initiates if condition
{
correct++; //sets condition for correct answers
}
else if (key[i] != answers[i]) //initiates if condition
{
incorrect++; //sets condition for incorrect answers
}
score = 40 - incorrect; //calculates score
}
cout << score << " "; //output student score
return score; //pass score
}
编辑以澄清:我需要代码显示如下:
关键:TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF 27 D
ADE62366 TTFTFTTTFTFTFFTTF__ 34 B(带_为空格)
它的显示方式如下:
关键:TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF 27 D
ADE62366 TTFTFTTTFTFTFFTTF 34 B
我认为这是一个对齐问题,因为我现在已经发布了一些代码。
答案 0 :(得分:2)
一些评论:
char answers[21];
inFile.getline(answers, 22);
您无法将21个字符读入21个大小的数组中。
answers >> length;
这没有任何意义。
for (i = 0; i < 22; i++) //initiates conditions for for loop
如果只有20个答案,为什么要循环到索引21?
score = 40 - incorrect; //calculates score
这可以在循环之后放置,但为什么不根据你的规则计算分数(2 *正确不正确)?