1

for the program I'm writing I need to find the location of a specific word inside a string array, but I don't know how. This is the code I made but it doesn't work:

 int location;
 string input;

 cout << "Type your name" << endl;
 cin >> input;

  for (int i = 0; i <= count; i++) 
    {
        call_DB[i].name;

    if (call_DB[i].name == input)
        {
            location = i;
        }
    }

What is wrong with that code and what can I do to fix it? Thank you.

CyberSoul
  • 11
  • 1
  • 1
    std::string::find ? – Steephen Mar 22 '17 at 03:18
  • Possible duplicate of [How to find substring from string?](http://stackoverflow.com/questions/13195353/how-to-find-substring-from-string) – CaptainTrunky Mar 22 '17 at 03:26
  • I don't think we have enough information to answer this question. Try examining the contents of call_DB[...] in your debugger, watching for whitespace. It may also be worthwhile to store your strings in some STL container like an std::set, std::unordered_set or std::map for quick ((O)log(N) or even (O)1 rather than (O)N) lookup times. – JeremiahB Mar 22 '17 at 03:28
  • You Need to Read [How to Ask a Query on Stack-overflow](https://stackoverflow.com/help/how-to-ask) – Prasad Mar 22 '17 at 03:49

2 Answers2

1

Try std::find_if, which searches the array for item satisfying provided predict function.

auto iter = std::find_if(call_DB, call_DB + count, [&input](const YOUR_CALL_DB_TYPE& item ){ return item.name == input; });

if(iter == call_DB + count) 
     printf("Not found\n");
else
     printf("Found: %s\n", iter->name.c_str());

If such item is found, the index is the distance from array base, size_t index = iter - call_DB;

Chen OT
  • 3,486
  • 2
  • 24
  • 46
1

You can get an iterator to the array element using std::find_if:

auto it = std::find_if(std::begin(db), std::end(db), [&name](auto const& x) {
  return x.name == name;
});

And if you want the index into the array:

auto index = it - std::begin(db);
Joseph Thomson
  • 9,888
  • 1
  • 34
  • 38