[英]Compare two strings in C++
我想將用戶輸入與存儲在字符串數組中的值進行比較。 我的數組是
string colours[] = {"Black","Blue","Green","Orange","Red","Yellow"};
用戶輸入分配給
CString selectedColor;
如何比較這些值?
我會怎么做:
#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
並進行比較,但這已被問到並回答: 如何轉換CString和:: std :: string :: std :: wstring互相嗎?
已經完成所有轉換的另一種可能的解決方案:
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.