0

Below is my code. Can somebody tell me how to perform a search in the struct for the field name? I tried with s.name but it does not work. As for the search with for loop (for(int i=0;i<length;i++) I do not know how to search in the struc

 #include<fstream>
    #include<iostream>
    using namespace std;
    
    struct Student
    {
        char name[50];
        int age;
        float gpa;
    };
    int main()
    {
        const int SIZE = 3;
        Student old_students[SIZE] = {
            { "John", 48, 3.58 },
            { "Tom", 25, 2.50 },
            { "Rick", 22, 3.90 }
        };
    
        fstream f;
        f.open("records.dat", ios::out | ios::binary);
    
        if (f.is_open())
        {
            f.write(reinterpret_cast<char*>(old_students), SIZE * sizeof(Student));
            f.close();
        }
        else
            cout << "ERROR\n";
    
        
        f.open("records.dat", ios::in | ios::binary);
    
        Student new_students[SIZE];
    
        if (f.is_open())
        {
            f.read(reinterpret_cast<char*>(new_students), SIZE * sizeof(Student));
            f.close();
        }
        else
            cout << "ERRROR\n";
    
    
        for (Student& s : new_students)
        {
            if (s.name == "John"){
                cout << s.name << endl;
                cout << s.age << endl;
                cout << s.gpa << endl;
            }
            
        }
    
        system("pause");
    }
  • "does not work" is a terrible diagnostic. Does your program crash? Did you step through it in a debugger to make sure `new_students` contains the right values? Are you aware that `==` on `char[]` does not do what you think it does? – Botje Oct 19 '21 at 11:47
  • 2
    You can't compare C-style strings (like the null-terminated array `s.name` is) or literal string constants (like `"John"` is) with each other. You need to use the old C string function `strcmp`. Or convert at least one of the strings to a `std::string` object. – Some programmer dude Oct 19 '21 at 11:48
  • `strcmp()` is your friend – Leos313 Oct 19 '21 at 11:53

0 Answers0