我想将用户输入与存储在字符串数组中的值进行比较。我的数组是
string colours[] = {"Black","Blue","Green","Orange","Red","Yellow"};
用户输入分配到
CString selectedColor;
如何比较这些值?
答案 0 :(得分:0)
我会做什么:
#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;
}
}
}
您还可以将CString
转换为std::string
并对其进行比较,或者将std::string
转换为CString
并进行比较,但这已经被问及并回答了已经:How to convert CString and ::std::string ::std::wstring to each other?
答案 1 :(得分:0)
另一种可能的解决方案,已经进行了所有转换:
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;
}
}