0

I want to compare user input with the values stored in an string array. My array is

string colours[] = {"Black","Blue","Green","Orange","Red","Yellow"};

User input is assign to

CString selectedColor;

How can I compare these values?

KMA
  • 211
  • 3
  • 17
  • What do you want to know? Is `selectedColor` contained in the `colours[]` array? Or what do you mean by _compare_? – outofmind Oct 07 '15 at 11:36
  • 3
    Why don't you stick to a single string class? Then you can just use relational operators to do whatever it is that you want. – Alex Díaz Oct 07 '15 at 11:38
  • selectedColur is the variable name given for the user input. I want to check whether it is in the colours array. – KMA Oct 07 '15 at 11:40
  • Try and look at http://www.cplusplus.com/reference/cstring/strcmp/?kw=strcmp for c string and http://www.cplusplus.com/reference/string/string/compare/ for `std::string` – Anders Schou Oct 07 '15 at 11:43
  • Unlike `string` (assuming you mean `std::string`), `CString` is not in the C++ standard library. You will need to read the documentation for whatever library you are using. Odds are there will be some ability to obtain a `char *` or a `const char *` from it. Such a pointer can be used to create a `std::string`, and then you can use standard techniques to compare. – Peter Oct 07 '15 at 11:44

2 Answers2

0

What I would do:

#include <iostream>

int main(void)
{
    std::string colours[] = {"Black","Blue","Green","Orange","Red","Yellow"};
    std::string input;
    std::cin >> input;
    for(const auto& color : colours) //c++11 loop, you can use a regular loop too
    {
        if(input == color)
        {
            std::cout << input << " is a color!" << std::endl;
        }
    }
}

You could also convert the CString to a std::string and compare them or the other way around convert the std::string to CString and compare but this has been asked and answered already: How to convert CString and ::std::string ::std::wstring to each other?

Community
  • 1
  • 1
Alex Díaz
  • 2,303
  • 15
  • 24
  • I'm getting this user input from a combo box (Drop down list). can I convert the combobox input type from CString to string? – KMA Oct 07 '15 at 11:54
  • 1
    @AlokaKulathilaka Yes you can, just follow the link or better yet declare your `colours` array as a `CString` array and avoid conversion altogether. Disclaimer: I have zero experience with VC++(which is what I'm assuming you're using) – Alex Díaz Oct 07 '15 at 11:59
0

Another possible solution, already with all conversions:

std::string colours[] = { "Black", "Blue", "Green", "Orange", "Red", "Yellow" };
CString selectedColor("Blue");

int colours_size = sizeof(colours) / sizeof(colours[0]);
for (int i = 0; i < colours_size; ++i) {
    CString comparedColor(colours[i].c_str());
    if (selectedColor.Compare(comparedColor) == 0) {
        std::cout << "Color found" << std::endl;
    }
}
maxteneff
  • 1,523
  • 12
  • 28