Reputation: 199
if I have:
const string food[] = {"Burgers", "3", "Fries", "Milkshake"}
string word;
cin >> word;
How can I compare word with the correct food? or rather, if the user inputs "Fries", how can I compare that with the string array?
Upvotes: 2
Views: 1968
Reputation: 254431
With the find
algorithm from <algorithm>
:
auto found = std::find(std::begin(food), std::end(food), word);
if (found == std::end(food)) {
// not found
} else {
// found points to the array element
}
or with a loop:
for (const auto &item : food) {
if (item == word) {
// found it
}
}
although, if you need to do this a lot, it might be better to store the items in a data structure designed for quick searches: std::set
or std::unordered_set
.
Upvotes: 3
Reputation: 476970
With find
:
#include <algorithm>
#include <iterator>
auto it = std::find(std::begin(food), std::end(food), word);
if (it != std::end(food))
{
// found *it
}
else
{
// not found
}
Upvotes: 7