-1

How do you accept case-insensitive and allow embedded blanks in a user input? So the user can enter “hong konG” and get a correct match to the input.

I only have the input[0] = toupper(input[0]); which only accepts if the case sensitive is at the beginning of the word.

while(true){
cout << "Enter a city by name: "<< " "; 
std::getline (std::cin,input);
if (input == "quit")
    {
        break;
    }
input[0] = toupper (input[0]);

    //....how do I loop to find all letter's in the input string variable?    
}
4

3 回答 3

4

您可以使用循环将整个字符串一次转换为大写一个字符,但更好的解决方案是使用 C++ 标准库的transform函数:

std::string hk = "hong konG";
std::transform(hk.begin(), hk.end(), hk.begin(), ::toupper);

这将适用::toupper于您的字符串的所有字符,从而生成一个读取为"HONG KONG".

ideone 上的演示。

于 2013-10-09T16:10:04.320 回答
2
for (auto& c : str)
    c = std::toupper(c)
于 2013-10-09T16:13:53.410 回答
0

您可以像这样将整个字符串转换为大写

for (size_t i = 0; i < input.size(); ++i)
    input[i] = toupper (input[i]);

另一个使用建议std::transform也是一个非常好的解决方案。

于 2013-10-09T16:12:43.520 回答