Сравнение элементов массива в C ++ - PullRequest
0 голосов
/ 09 августа 2010

У меня есть программа домашней работы, по которой мне нужно немного помочь. Мне нужно сравнить массив, содержащий ключ ответа теста, с массивом, содержащим ответы студента. Проблема, с которой я сталкиваюсь, заключается в том, что мне нужно принять во внимание пустые ответы. Я не могу придумать код, который будет сравнивать массивы, а затем отображать счет. Тест оценивается как 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

Что, я думаю, является проблемой выравнивания, так как я сейчас написал кое-какой код.

1 Ответ

2 голосов
/ 09 августа 2010

Некоторые замечания:

    char answers[21];
    inFile.getline(answers, 22);

Вы не можете прочитать 22 символа в массиве размером 21

answers >> length;

Это не имеет никакого смысла.

for (i = 0; i < 22; i++)  //initiates conditions for for loop

Почему вы переходите к индексу 21, если у вас есть только 20 ответов?

    score = 40 - incorrect;  //calculates score

Это может быть размещено после цикла, но почему не рассчитывается счет в соответствии с вашими правилами (2 * правильно-неправильно)?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...