-2

I'm working on a midterm project for my coding class, and while I've gotten the majority of kinks worked out I'm struggling with comparing two string values and determining if they are equal or not. The strings in question are ANSWERKEYand studentAnswers. The former is a constant that the latter is compared to.

The code in question is as follows.

if (studentAnswers == ANSWERKEY)
    {
        percentScore = 100.0;

        cout << "Score: " << percentScore << " % " << 'A' << endl;
    }

    else if (studentAnswers != ANSWERKEY)
        {
            int count = 0;
            double answerCount = 0.0;
            while (count < ANSWERKEY.length())
                {
                    if (studentAnswers.substr(count, count+1) == ANSWERKEY.substr(count, count+1)
                        {
                            answerCount++;
                            count++;
                        }
                    else
                        {
                            cout << "Incorrect answer." << endl;
                            count++;
                        }
                }
        percentScore = ((answerCount) / (double)ANSWERKEY.length()) * 100.0;
        cout << "Percent score is " << percentScore << "%" << endl;
        }

The exact issue I'm facing is that I can't work out a better way to compare the strings. With the current method, the output is the following:

The intro to the code runs fine. Only when I get to checking the answers against the key, in this case "abcdefabcdefabcdefab", do I run into issues. Regardless of what characters are changed, the program marks roughly half of all characters as mismatching and drops the score down because of it.

I've thought of using a pair of arrays, but then I can't find a solution to setting up the array when some values of it are empty. If the student's answers are too short, e.g. only 15 characters long, I don't know how to compare the blank space, or even store it in the array.

Thank you for any help you can give.

Community
  • 1
  • 1

1 Answers1

1

First:

if (studentAnswers == ANSWERKEY)
{...}
else if (studentAnswers != ANSWERKEY)
{ ...}

looks like an overkill when comparing strings. And where is the else part ?

Second, this is risky. Read the IEE754 and articles about cancellation, or even SO:

double answerCount = 0.0;
...
answerCount++

Third:

You are checking character by character using substr. To me it feels like using a hammer to kill a bacteria.

studentAnswers.substr(count, count+1) == ANSWERKEY.substr(count, count+1)

Fourth:

What if studentAnswers is shorter than ANSWERKEY ?

Conclusion: You need to clarify inputs/expected outputs and use the debugger to better understand what is happening during execution. Carefully check all your variables at each step fo your program.

LoneWanderer
  • 3,058
  • 1
  • 23
  • 41