C++ question How to compare two int if they are the same? I recieve this error:
ID: 3833880 • Letter: C
Question
C++ question
How to compare two int if they are the same? I recieve this error:
In function 'int main()':
error: invalid types 'int[int]' for array subscript
if (target[i] == friends[n].idnum[i]) //compare Ints
^
error: invalid types 'int[int]' for array subscript
if (target[i] == friends[n].idnum[i]) //compare Ints
My code:
in.open(input.c_str());
if (!in)
cout << "Error opening file." << endl;
else
{
int target;
int n2 = 0;
in >> target;
while (in)
{
in >> target;
n2++; //How many targets
for (int i = 0; i < n2; i++)
{
if (target[i] == friends[n].idnum[i]) //compare Ints
{
outf << "ID#: " << friends[i].idnum << endl;
outf << "Name: " << friends[i].firstname + ',' + friends[i].lastname << endl;;
outf << "Test score: " << friends[i].score << endl;
outf << "Test responses: " << friends[i].answers << endl;
outf << endl;
}
else
{
outf << target << "is not a valid student ID# " << endl;
}
}
}
in.close();
}
Desired output:
ID#: 56
Name: Larry Black
Test score: 95
Test responses: abcdabcdabcdabcdabcbbbbbbbb
13 is not a valid student ID#
ID#: 10
Name: Matthew Adams
Test score: 15
Test responses: aaaaaaaaaaaa
ID#: 19
Name: Jennifer Schwartz
Test score: 75
Test responses: aabbcccdabcdabcdabcd
-5 is not a valid student ID#
Explanation / Answer
Variable target is declared as an integer variable.
In the statement: if(target[i] == friends[n].idnum[i]) , target is used as an array.
Structure array friends is accessed using index variable i. Feild idnum is accessed as friends[i].idnum
Change the above statement as follows:
if(target == friends[i].idnum)
This will resolve the issue.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.