Array of objects through search.

Hell comrades, as a computer science student, am trying to work out on some assignments given to me. Am working on a program that should allow the user to do a search of the book’s titles among the given data of titles of the books and be able to do a display of the information. Is anyone of you capable of guiding me through and let me know why the program below is not working?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if(option == 2)
    {
        cout << "What book would you like details for?: ";
        cin >> bookName;

        for (int i = 0; i < max; i++)
            {
               if(bookName = libBooks[i].getTitle()){

                cout <<"Book "<< i+1 <<": ";
                libBooks[i].output();
               }
            }

    }

https://www.theengineeringprojects.com/2019/11/introduction-to-abstract-classes-in-c.html
Last edited on
1
2
// if(bookName = libBooks[i].getTitle()){
if(bookName == libBooks[i].getTitle()){ // == 
In c/c++ = is assignment, == is equality comparison.

the result of an assignment is the value of the assignment. So in L8 bookName is assigned the value of libBooks[i].getTitle(). This value is then tried to be converted to bool for the if condition. if there is no available conversion, then the compiler will issue an error. In any case in this situation the compiler should issue a warning.

You don't state the type of bookName. If this is of type std::string, then == will work. However if bookName is of type char*/char[] (c style null terminated string), then you need strcmp() for the comparison.
Last edited on
> However if bookName is of type char*/char[] (c style null terminated string),
> then you need strcmp() for the comparison.

Not necessarily; even if bookName is a null-terminated character string,
if libBooks[i].getTitle() is of type std::string or std::string_view, == can be used for equality comparison.

Even if both are c-style strings, == can still be used for equality comparison, with an explicit conversion:
if( std::string_view(bookName) == etc.
Topic archived. No new replies allowed.