将char array []与char * array []进行比较?

时间:2017-02-12 17:16:28

标签: c++ arrays string

很抱歉,如果标题中的术语不正确,但基本上我想将char数组与包含字符串文字的char *数组进行比较。 基本上我有一个数组:

char temp[6];
cin.get();
cout << "Enter: ";
cin.getline(temp,6);

char *compare[10] = {".- ", "-... ", "-.-. ", "-.. ", ". ", "..-. "};

如何将用户输入的字符串与“compare”数组元素进行“temp”比较。例如,如果用户输入:“ - 。”,它将输入的字符串与“compare”的每个元素进行比较,并检查它是否匹配? 我试过做比较,但总是给我一个错误,说“ISO C ++禁止指针和整数之间的比较[-fpermissive] |”

2 个答案:

答案 0 :(得分:1)

您应该始终使用STL的设施。这样你就可以改变这种喧嚣:

char temp[6];
cin.get();
cout << "Enter: ";
cin.getline(temp,6);

char *compare[10] = {".- ", "-... ", "-.-. ", "-.. ", ". ", "..-. "};

为:

std::string temp;
std::cout << "Enter: ";
std::getline(std::cin, temp);

std::vector<std::string> compare = {".- ", "-... ", "-.-. ", "-.. ", ". ", "..-. "};

现在查找输入的字符串是否匹配:

auto iter = std::find(compare.begin(), compare.end(), temp);
if(iter != compare.end(){
     // You have a match!
}

一个完整的例子:

#include <algorithm>
#include <iostream>
#include <vector>

int main(){

    std::string temp;
    std::cout << "Enter: ";
    std::getline(std::cin, temp);

    std::vector<std::string> compare = {".- ", "-... ", "-.-. ", "-.. ", ". ", "..-. "};

    auto iter = std::find(compare.begin(), compare.end(), temp);
    if(iter != compare.end(){
         //To obtain index from an iterator
         auto index = std::distance(iter, compare.end());

         std::cout << "We found a match at: " << index << '\n';
    }

}

如果您对上述代码有很多疑问,可能需要查看The Definitive C++ Book Guide and List

答案 1 :(得分:0)

您应尽可能使用STL功能。在您当前的情况下,请尝试使用std::string代替char*std::vector代替char* arr

您可以替换现有代码

char temp[6];
cin.get();
cout << "Enter: ";
cin.getline(temp,6);

char *compare[10] = {".- ", "-... ", "-.-. ", "-.. ", ". ", "..-. "};

通过这个

std::string temp;
std::cout << "Enter: ";
std::getline(std::cin, temp);

std::vector<std::string> compare = {".- ", "-... ", "-.-. ", "-.. ", ". ", "..-. "};

现在你可以通过像

这样的比较向量进行迭代
for(const auto& iter : compare) {
    // Do the comparison to check whether it's a match or not.
}
相关问题