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.

4
  • 1
    std::string::find ? Commented Mar 22, 2017 at 3:18
  • Possible duplicate of How to find substring from string? Commented Mar 22, 2017 at 3: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. Commented Mar 22, 2017 at 3:28
  • You Need to Read How to Ask a Query on Stack-overflow Commented Mar 22, 2017 at 3:49

2 Answers 2

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;

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.