Evan
Evan

Reputation: 355

ISO C++ forbids comparison between pointer and integer?

Here is the code:

void option5 (StudentRecord student[], int n)

{
   double gpaThreshold;
   char enteredMajor;
   int i;

   cout << "Enter a GPA threshold: ";
   cin >> gpaThreshold;
   cin.ignore(80, '\n');

   cout << "Enter a Major: ";
   cin >> enteredMajor;
   cin.ignore(80, '\n');

   enteredMajor = toupper(enteredMajor);

   for (i = 0; i < n; i++)
   {
      if (student[i].gpa >= gpaThreshold && student[i].major == enteredMajor)
      {
         if (i % 10 == 0)
         {
            cin.ignore();
         }
         cout << setw(3) << right << i+1 << ". "  
         << setw(20) << left << student[i].lastName 
         << setw(20) << left << student[i].firstName 
         << setw(8) << left << student[i].major 
         << fixed << setprecision(2) << setw(8) << left << student[i].earnedHours 
         << fixed << setprecision(2) << setw(6) << left << student[i].gpa << endl;
      }
   }
}

StudentRecord is a struct, and the only integer on that line is 'i', whereas the pointer (I would have to assume) is .major.

I'm wanting to compare an entered major, with the "Major" values in the array. E.G. I type in Chem -turns to CHEM -fetches all students under that major (and threshold of GPA) -displays the above statement (all students of 'X' major)

Any suggestions? Help? Comments? Positive/Negative Feedback?

EDIT: Here is the struct:

struct StudentRecord
{
   char     lastName [16];  // field definitions of the structure
   char     firstName[16];
   char     hometown [16];
   char     major[5];
   int      studentNumber;
   double   balance;
   int      earnedHours;
   double   gpa;
};

Upvotes: 0

Views: 4343

Answers (2)

Robᵩ
Robᵩ

Reputation: 168626

Consider this fragment:

student[i].major == enteredMajor

student[i].major is a char[5], which devolves into a char* in this context. This is a pointer type.

enteredMajor is a char. This is an integral type.

You cannot compare these types.

Perhaps you meant to decalre enteredMajor thus:

char enteredMajor[5];

and compare them like this:

strcmp(student[i].major, enteredMajor) == 0

Upvotes: 2

Pete Becker
Pete Becker

Reputation: 76245

student[i].major is a char array; when used in an expression it decays into a pointer to char. The code compares it for equality with enteredMajor which has type char. Thus the complaint: can't compare a pointer and an integer (because char gets promoted to int).

Upvotes: 1

Related Questions