C ++比较字符串和字符串数组 [英] C++ comparing a string with an array of strings

查看:69
本文介绍了C ++比较字符串和字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有

const string food[] = {"Burgers", "3", "Fries", "Milkshake"}
string word;
cin >> word;

我如何比较单词和正确的食物?或者更确切地说,如果用户输入"Fries",该如何与字符串数组进行比较?

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?

推荐答案

使用查找:

#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
}

这篇关于C ++比较字符串和字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆