search for an element in an array

I'm trying to write this function that is supposed to return true if an element in this array is found and it is being compared to user input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void ViewBookInfo(BookType b[], int& bookCnt)
{
  bool found = false;
  string isbn;
  cout << "Please enter ISBN: ";
  cin >> isbn;
  SearchBooks(b, bookCnt, isbn, found);


  if(found)
    cout << endl << b[bookCnt].GetTitle() << endl;
  else
    cout << "Not a valid ISBN, returning to main menu.\n";
 return;
}

void SearchBooks(BookType b[], int& i, string isbn, bool& f)
{
  i = 0;
  while((!f) && (i < 200))
  {
    if(b[i].GetISBN() == isbn)
      f = true;
    else
      i++;
  }
 return;
}


So if I enter the first element in the array by hand, it will return true and output the title of the book corresponding to the ISBN. But, whenever I test an ISBN that isn't first in the array (even 2nd or 3rd) it returns false.
Last edited on
Hi,

what does GetISBN() return ?
If that is a string as i think, you can maybe try the "compare" method.
Don't know what happens in GetISBN() anyway, but well, it can also occur because of the way you call your functions ... might try C style "int* " inputs ?
On line 1 the bookCnt is revealed to be a reference. Is that intentional? Is a caller's variable supposed to change within ViewBookInfo as it does now?


You could consider a different approach:
1
2
3
4
5
6
7
8
9
10
11
12
13
// return N or position, where element's bar() equals bar
size_t foo( const T * array, size_t N, const std::string & bar ) {
  size_t pos = 0;
  while ( pos < N && array[pos].bar() != bar ) ++pos;
  return pos;
}


const size_t Num = ...
T items[num];

size_t found = foo( items, Num, "Hello" );
if ( found < Num ) std::cout << items[found].bar() << " world";
I thought it was ... i think for it all to work as intended ...
A question: What is "bookCount" when the function returns "false" ??
Topic archived. No new replies allowed.