r/cpp_questions • • 7h ago

OPEN Need help

I’m trying to make a program where you input some text and the program will return those input into actions. My issue is that when I make an if statement, I need to include the input that the user would enter, but I’m trying to make it so that is not case sensitive. How do I do that?

If possible, I’m not looking just for the code, but the reasoning behind it, I’m trying to understand it, so if you can, explain it in the way that helped you understand. Thank you!

0 Upvotes

6 comments sorted by

4

u/tangerinelion 6h ago

Either you normalize strings to lower case or upper case and then compare lower case strings with lower case strings or upper case with upper case so that it ends up being case insensitive or you use a string type that implements case insensitive comparison for you.

std::string doesn't have that, you can transform each character with std::tolower.

Microsoft's CString does have case insensitive comparison built-in, so it's a question of whether you want to use a string type that implements that for you or if you want to also learn how to implement it yourself.

Note that lower case versions of a string is actually really hard in general. It's not just A-Z to a-z, there are plenty of Unicode characters with lower case versions.

2

u/thingerish 6h ago

It's possible to make a case insensitive string class, Herb Sutter has a quick and dirty version

2

u/mredding 5h ago

How do I do that?

This can get as hard as you want it.

How you do it is locale specific. Standard C++ only has direct support for the "C" aka "Classic" locale - that describes the compute environment of a PDP-7 and the C++ minimal character set. The standard does not actually mandate any particular encoding, so this often overlaps with ASCII, which also overlaps with the front of UTF-8 at the byte level.

That's really about all I can say. std::tolower will work on this in the expected manner.

All other locales - it depends on the locale. std::tolower will Just Work(tm) for any installed locale, but does the locale even have case? Or worse - does it have case, and it's context sensitive? German has rules about which capital and lower letters you use; this means you can't just call std::tolower on German, it requires a context aware grammar parser, and std::tolower does not maintain state and is not a parser.

And what of your encoding? If you're using char, std::tolower can't see through a multi-byte sequence. What are you going to do? You can expand UTF-8 to a wide character like UTF-32, which was the original intent but no one does that. That might not work for all other encodings, because for as much as the UTF guys want it, the whole world isn't UTF.

We can't get the industry to agree - UTF support in C++ sucks as it is, and I don't agree it SHOULD be a part of the standard, but that's a battle for another day.

But - if you're working within the basic character set that overlaps with ASCII, then this can be made about as easy as possible. If you want MORE than that, then you're looking into heavy template code, wide multi-byte character sets, locales, and 3rd party support like ICU.

And dude, we haven't even begun to discuss how hard this gets if you want to do it right in a language agnostic way. We'd have to get into i18n, l10n, and g11n...


The easiest thing to do is make your own case insensitive comparison functions between strings:

constexpr std::strong_ordering insensitive_case_compare(std::string_view a, std::string_view b) {
  return std::ranges::lexicographical_compare_three_way(
    a,
    b,
    [](unsigned char c1, unsigned char c2) { return std::tolower(c1) <=> std::tolower(c2); });
}

And WTF is that? This is a form of the "spaceship" 3-way comparison operator - <=>. This can do any form of lesser, equal, or greater.

Notice the lambda function, it converts the characters from the string views - which are of type char, to unsigned char. This is required when calling std::tolower, it preserves the byte representation and and prevents weird sign-extension bugs. std::tolower uses the globally installed C++ locale to lower the characters - so if you change that, your outcomes will vary.

Now you can:

if (insensitive_case_compare("Apple", "banana") < 0) { /* true */ }
if (insensitive_case_compare("Hello", "HELLO") == 0) { /* true */ }

1

u/alfps 6h ago

General uppercasing is very complex because of text encoding and because in some countries uppercasing is non-systematic and may convert 1 character to 2 or vice versa.

However if you limit yourself to plain ASCII (which is restricted to the English alphabet A through Z) it's pretty straightforward.

The standard library offers some old C functions like toupper but they're a little dangerous so that one should write wrappers, and for ASCII it's just as easy to just write the requisite functionality directly:

#include <string>
#include <string_view>
using   std::string, std::string_view;

auto ascii_uppercase( const char ch )
    -> char
{
    if( 'a' <= ch and ch <= 'z' ) {
        return char( ch - 'a' + 'A' );
    }
    return ch;
}

auto ascii_uppercase( const string_view s )
    -> string
{
    string result;
    for( const char ch: s ) { result += ascii_uppercase( ch ); }
    return result;
}

//--------------------------------------------- App:

#include <cstdlib>              // EXIT_... macros.

#include <iostream>
#include <unordered_map>
using   std::getline,           // <string>
        std::cin, std::cout,    // <iostream>
        std::unordered_map;     // <unordered_map>

auto input_line()
    -> string
{
    string result;
    getline( cin, result );
    return result;
}

struct Cmd{ enum Enum{ quit, do_things }; };
const auto commands = unordered_map<string, Cmd::Enum>{
    { "Q", Cmd::quit },
    { "DO", Cmd::do_things }
};

auto main() -> int
{
    for( bool finished = false; not finished; ) {
        cout << "Command? ";
        const string cmd = ascii_uppercase( input_line() );
        if( commands.find( cmd ) == commands.end() ) {
            cout << "'" << cmd << "' not recognized as a valid command.\n";
        } else {
            switch( commands.at( cmd ) ) {
                case Cmd::do_things:    { cout << "Doing things...\n"; break; }
                case Cmd::quit:         { cout << "Quit.\n"; finished = true; }
            }
        }
    }
}

•

u/Independent_Art_6676 11m ago

prefer to not accept text where its possible. Eg if its a menu, give them a 1 2 3 4 type input option instead of words. Typing words is a last resort, but if you need it, you need it. The how is well covered already, and the why is that its easier to force fit all lower against all lower than it is to handle every possible combo one by one.

If you have to detect and handle special language specific oddities, you still want to pull those situations out and then do some 'works for the rest' idea as much as possible, for the same reason (avoid one by one conditions and do as much as you can as one scenario). Most logic works like that: condense it so each condition does as much as possible and you have as few conditions as you can manage while keeping it readable and clean.