I'm making a program of a quiz but I'm having a problem with arrays of strings and the function strcmp
I think I might have to use pointers but I do not know which to assign as a pointer
#include <iostream>
#include <cstring>
#include <stdio.h>
#include <string.h>
#include <cmath>
using namespace std;
int main(){
char question1[5][1000]={"Question #1\n\nWhat is the formula for the area of a square?\n\nA.) Area = (Side)(Side)\nB.) Area = Side + Side\nC.) Area = Base + Height\nD.) Area = (pi)(Radius)(Radius)\nAnswer: ",
"Question #2\n\nWhat is the perimeter of a rectangle with length = 4 and width =8?\n\nA.) Perimeter = 4 + 8 = 12 units\nB.) Perimeter = (4)(8) = 32 units\nC.) Perimeter = 2(4) + 2(8) = 24 units\nD.) Perimeter = [2(4)][2(8)] = 128 units\nAnswer: ",
"Question #3\n\nWhat is the circumference of a Circle with Diameter = 10 units?\n\nA.) Circumference = (pi)(5)(5) = 78.5 units\nB.) Circumference = 2(pi)(5) = 31.41 units\nC.) Circumference = (pi)(10)(10) = 314 units\nD.) Circumference = 2(pi)(10) = 62.8 units\nAnswer:",
"Question #4\n\nWhat is the measurement for the side of a square with Perimeter = 80?\n\nA.) 20 units\nB.) 80 units\nC.) 40 units\nD.) 50 units\nAnswer: ",
"Question 5\n\nWhat is the radius of a circle with area = 64pi square units?\n\nA.) 2pi units\nB.) 4pi units\nC.) 6pi units\nD.) 8pi units\nAnswer: "};
char answer1[5][2]={"A","C","B","A","D"};
char answer;
int score,i;
for(i=1;i<5;i++){
cout<<question1[i];
cin>>answer;
if(strcmp(answer,answer1[i])==0)
{
score++;
}
}
cout<<"Your score is "<<score;
}
answer
is a single character and not a string. You can't use it as a string when passing it to functions expecting string. The call to strcmp
should have caused the compiler to emit a warning about this.
Compare the character directly, as e.g. answer == answer1[i][0]
.
Or change the type to a string (std::string
preferably, otherwise an array of char
).
On an unrelated note, you don't initialize the variable score
. That means its value will be indeterminate and using it (like in score++
) will lead to undefined behavior.
You need to explicitly initialize it:
int score = 0, i;