我正在尝试比较我的数组元素,但是当我编译它时,类成员数组没有显示我从主“键”中的原始数组复制到数组中的值,但是主数组“答案”保持我输入的值,并在程序运行后编写了一个测试循环,只是为了查看类成员数组“canswers”里面的内容,它是我从主“key”复制到数组中的实际变量。我正在尝试比较类函数“grade”中的两个数组(“canswers”和“answer”),但我不知道我做错了什么。每次我通过 for 循环比较它们时, if 语句,它不起作用,并出现随机字符。我在数组的最后写了一个测试循环来显示类成员数组“canswers”的内容,它具有我从 main 复制的所有正确值,但是当我比较时它没有显示或工作二。我试图保持代码尽可能干净,以便你们可以轻松阅读它。
#include<iostream>
#include<string>
using namespace std;
class TestGrade
{
public:
void setKey(char []);
void grade(char []);
char canswers[];
void display();
};
void TestGrade::setKey(char answers[]) //setting values from "key" array in main
{
for(int index = 0; index < 19; index++)
{
canswers[index] = answers[index];
}
}
void TestGrade::grade(char answer[]) //comparing elements in array, here's where the
{ //trouble begins
for(int index = 0; index < 19; index++)
{
cout << canswers[index] << " " << answer[index] << endl;
if(canswers[index] == answer[index])
{ cout << "The values are equal" << endl;}
}
}
void TestGrade::display() //testing the values after the loop i had trouble with
{
for(int index = 0; index < 19;index++)
{
cout << canswers[index] << endl;
}
}
int main()
{
const char SIZE = 20;
char answer[SIZE];
char key[20] = {'B', 'D', 'A', 'A',
'C', 'A', 'B', 'A',
'C', 'D', 'B', 'C',
'D', 'A', 'D', 'C',
'C', 'B', 'D', 'A'};
TestGrade test1,test2;
test1.setKey(key);
cout << "Welcome to the written portion of the DMV exam. \n";
cout << "You may only enter capital A, B, C, or D for your answers.\n\n" << endl;
for (int index = 0; index < SIZE; index++)
{
cout << "Enter your answer for question " << index+1 << endl;
cin >> answer[index];
while (answer[index] != 'A'
&& answer[index] != 'B'
&& answer[index] != 'C'
&& answer[index] != 'D')
{
cout << "ERROR: you must input capital A,B,C, or D" << endl;
cin >> answer[index];
}
}
test2.grade(answer); // comparing the values of canswer[] and answer[]
test1.display(); //test loop testing contents of canswers[] class member array
system("pause");
return 0;
}