-2

Sorry if the terminology in the title is incorrect but basically I want to compare a char array with a char * array that contains string literals. Basically I have an array:

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

And:

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

How do I go about comparing the string entered by the user into "temp" with the "compare" array elements. Example if user enters: " -... " it compares the string entered with every single element of "compare" and check if it matches? I have tried doing comparisons but it always gives me an error saying " ISO C++ forbids comparison between pointer and integer [-fpermissive]|"

slowjoe44
  • 7
  • 3

2 Answers2

1

You should use the facilities of the STL wherever applicable always. So that you can change this hullabaloo:

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

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

to:

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

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

Now to find whether the entered string matches:

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

A full example:

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

}

If you have lots of questions about the code above, you probably want to check The Definitive C++ Book Guide and List

Community
  • 1
  • 1
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
0

You should use STL feature as much as possible. In your current scenario try using std::string instead of char* and std::vector instead of char* arr.

You can replace your existing code

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

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

By this

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

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

Now you can iterator over this compare vector like

for(const auto& iter : compare) {
    // Do the comparison to check whether it's a match or not.
}
Shravan40
  • 8,922
  • 6
  • 28
  • 48