I tried searching the forum, but I couldn't find any threads that really dealt with what I'm trying to do here.

I have a struct set up with three fields (shown below).

struct StudentInfo {
    char id[10];
    double mark;
    char grade;
};

Note that the id MUST be a C-string.

I have then made an array of several of these structs, the length of this array depends on how many times the user runs the "enter information" option which looks like this:

cout << "Enter the student ID (max. 10 chars): ";
cin >> array[runCount].id;
cout << "Enter the mark: ";
cin >> array[runCount].mark;
while (array[runCount].mark > 100 || array[runCount].mark < 0)
{
    cout << "Enter a valid mark between 0 and 100" << endl;
    cin >> array[runCount].mark;
}

// Apply corresponding mark
if (array[runCount].mark < 50)
   array[runCount].grade = 'F';
else if (array[runCount].mark < 65)
   array[runCount].grade = 'P';
else if (array[runCount].mark < 75)
   array[runCount].grade = 'C'; 
else if (array[runCount].mark < 85)
   array[runCount].grade = 'D'; 
else
   array[runCount].grade = 'H';

cout << "\n\nYou have added the following record:\n"
     << "------------------------------------\n"
     << "ID: " << setw(10) << array[runCount].id << endl
     << "Mark: " << setw(5) << setprecision(2) << fixed << array[runCount].mark << endl
     << "Grade: " << array[runCount].grade << endl << endl;

runCount++;

What I want to do is compare this id field inside the struct with another C-string entered into the console so I can construct a kind of search function to find a given ID. So create another C-string called query[10] and compare it against all of the C-strings in each struct of the array of structs (array.id) for any given i.

I've tried to make functions that pass the entire array of structs to it and search within it but nothing I've tried seems to work yet.

Any help will be much appreciated.

Recommended Answers

All 2 Replies

Member Avatar for iamthwee

Should be able to just do a comparison.

Maybe using the c-style string compare function. Can't remember what it is cos I never use c-style strings in c++

Should be able to just do a comparison.

Maybe using the c-style string compare function. Can't remember what it is cos I never use c-style strings in c++

Thank you. I completely forgot about the cstring functions. Turns out strcmp is what I needed. I'll post what I did in case anyone else has the same problem:

for (int k = 0; k < runCount; k++) {
    if (strcmp(array[k].id, query) == 0)
    {
        cout << "Entry " << k << endl;
        break;
    }
}

(since strcmp returns 0 when the cstrings match.)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.