Hi there,
I've been learning C lately, and in one of the exercises I've encountered a bit of a frustrating issue. The exercise is to accept a string of characters that are answers to a multiple choice quiz, and then compare them to the correct answers which are in another string.
It's mostly working fine, but I'm having an issue when comparing the first element in the string. No matter what the letter is, the program always says it's the same in both strings, when it's definitely not. The strange thing is that otherwise the program works fine - it will correctly determine if an answer is correct or not for all other elements in the string. Just the first one is having the issue. My code is below:
int main()
{
char correct[]= "ABBDCEACBEDBBCC";
char exam[15];
char grade[1];
int count, score, length = (strlen(correct)+1);
printf("Enter an answer string or q to quit\n");
gets(exam);
score = 0;
while(exam[0] != 'q')
{
for(count = 0; count <= length; count++)
{
exam[count] = toupper(exam[count]);
//printf("count is at %d\n %s", count, exam);
if (exam[count] == correct[count]) score += 1;
}
switch(score)
{
[cases to determine a letter grade by checking the score]
}
printf("Score = %d, grade = %c", score, grade[0]);
printf("\n\nEnter an answer string or q to quit\n");
scanf("%s", exam);
score = 0;
}
return 0;
If I put an if statement in to look for the first element, it fixes the issue:
if (count == 0 && exam[0] != 'A') score -=1;
But that's not really an elegant solution. If any one could give me a hint as to why the first element isn't being compared, that would be great.
Cheers