不区分大小写的比较

时间:2015-01-02 01:18:25

标签: c++ string case-insensitive

很抱歉打扰这个。这是一个基本功能,但我仍然是C ++的整个领域。我试图允许任何形式的“你好”这个词。我希望程序允许输入任何形式的hello,无论用户如何输入单词(即大写,小写或混合)。随意批评,我只是想学习。 :)

int instructions() 
{

    string intro;

        do
        {
            cout << "Greet me with 'hello' to continue: " << intro;
            cin >> intro;

        } while (intro != "hello");

        cout << "Welcome! What shall I call you?  ";
        cin >> name;
        cout << "\nHello " << name << "! ";

    return 0;
}

1 个答案:

答案 0 :(得分:1)

您可以使用一些功能,但tolower是首先想到的。由于lambda,此解决方案要求您使用C ++ 11标准。如果你不能告诉我,我会提供替代方案。

#include <cctype>
#include <algorithm>
#include <iostream>

int instructions() 
{
    string intro; 

    do {

        cout << "Greet me with 'hello' to continue: ";
        cin >> intro;

        for_each(intro.begin(), intro.end(), [](char &a) {
            a = tolower((unsigned char)a);
        });

    } while (intro != "hello");

    return 0;
}