2

so i got that first problem working. i run the code and i am prompt to enter some list into the array. after entering the list i run this function as a search_func. but it keeps return no record found. is it because of [0], odd because i have it within a for loop.

Please help. book books[] is a class object..

int search(book books[], char search) {
    const char* boook =books[0].gettitle();
  //......try this but it failed please help
  cout << "Search books by title:____  ";

  cin >> search;

  bool yes = false;
  int size=2;

  for(int index=0; index<size; index++) {
    if(strcmp(boook,search) == 0 )//....error at this line
         { 
        found = true;
        cout<<"book found "<<endl;
        //cout<<"Author Name: "<<fn<<" "<<ln<<endl;
        break;
      }
  }

  if(!yes)
    cout<<"no book found"<<endl;
}
2
  • Try books[0].gettitle().c_str(); ? Commented Oct 30, 2011 at 2:54
  • 3
    You're mixing C and C++. Either use arrays and C functions, or vectors and std::string. std::string works with ==; no need for antiquated strcmp. Commented Oct 30, 2011 at 3:00

2 Answers 2

4

Try this:

const char* c_str = books[0].gettitle().c_str();

http://www.cplusplus.com/reference/string/string/c_str/

EDIT:

If gettitle() returns a temporary, then the above method won't work. You will need to do this instead:

string title = books[0].gettitle();
const char* c_str = title.c_str();
Sign up to request clarification or add additional context in comments.

5 Comments

u dont know if gettitle() returns a temporal string object, if that's the case, this code will yield undefined behaviour when trying to use c_str
thanks that took care of that part. didnt know i needed to put .c_str() at the end
@smerlin: Yes, that is a possibility. I'll fix my answer to address that.
The reason is this: If a temporary is returned. It is destroyed after the statement ends. At which the pointer returned by c_str() is no longer valid. I have updated my answer to address this issue.
you can either store the std::string returned by gettitle() in a named std::string variable, or pass the const char* returned by c_str() directly to strcmp. If gettitle() returns a std::string& or a const std::string&, the old code was fine.
0

I am assuming the first argument is a std::string. Try calling it's c_str() method.

2 Comments

search is a char (its in the question, but not correctly formatted in the code block)
@smerlin: It should be a char*, pointing to an array. Or, better, a std::string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.