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?
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?
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?
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;
}
}