Search code examples
cstrcmp

Error using strcmp with char and struct arrays


I have a program in which I have an array of 10 struct variables called students. Within students I have a char array variable called testAnswers with 20 elements. What I am trying to do is to compare these ten students' testAnswers with a char array variable called answers with 20 elements. Basically, variable answers is the answer sheet for the students' testAnswers. The answers are all true/false. This is what I have so far:

Note: numStu is 10 and numAns is 20.

void checkAnswers(char  answers[], student students[]){

for (int i = 0 ; i < numStu ; i++){
for (int d = 0 ; d < numAns ; d++){

if (students[i].testAnswers[d] == ' '){
          students[i].score += 1 ; //if the student did not answer the question add 1     which will be substracted once if loop sees it is not correct resulting in the         student losing 0 points.                   
                               }
  if (strcmp(answers[d],students[i].testAnswers[d]) == 0){
              students[i].score +=2 ;//if the student answer is correct add 2 points    to score
              }
  if (strcmp(answers[d],students[i].testAnswers[d]) != 0){
              students[i].score -= 1 ; //if the student answer is incorrect substrct 1    point
              }

}//end inner for
}//end for outer
  }//end checkAnswers

The errors I continue to receive:

invalid conversion from char to const char
initializing argument 1 of `int strcmp(const char*, const char*)' 

For both instances where I used strcmp. I am wondering if there is anyway to correct this error or any better way to compare these two chars and score the test.


Solution

  • strcmp is to compare to strings (sequences of characters), not single characters.

    You can just use an equality check for single characters:

    if (answers[d] == students[i].testAnswers[d])
    

    Note that if we're talking about boolean values, using an explicit boolean type is probably better than char.