any way to read in and make lower case in same step?

136 views Asked by At

I'm reading in user input via

string word;
while(cin >> myWord)
    //put myWord in array

but for the sake of sorting I want "This" and "this" to be the same. For my sort algorithm I'm using the default < and > values for string, so This != this, and for my purposes I need it to == so I want to just immediately make everything lowercase while it's read in. From the tolower I see I would need to make a for loop to iterate through word and make it lowercase, so I'd need to do this inside of the while loop before putting the word into the array. But I'm wondering if there's any trick I can do to make put the word from cin into myWord already lower case (or make "myWord" lower case right after being read in) in one line, along the lines of cin >> myWord.lower is what I'm talking about

2

There are 2 answers

0
vsoftco On

That's how I would do it, by using a custom sorting predicate for std::string

#include <algorithm>
#include <iostream>
#include <locale>
#include <string>

struct SortNoCase // functor used to sort strings ignoring the case
{
    bool operator()(const std::string& lhs, const std::string& rhs) const
    {
        std::string lhs_lower, rhs_lower;
        std::transform(std::begin(lhs), std::end(lhs), 
            std::back_inserter(lhs_lower), ::tolower);
        std::transform(std::begin(rhs), std::end(rhs), 
            std::back_inserter(rhs_lower), ::tolower);
        return lhs_lower < rhs_lower;
    }
};


int main ()
{
    std::vector<std::string> vs{"Some", "strings", "THAT", "are", "UnSorted"};

    std::sort(std::begin(vs), std::end(vs), SortNoCase());

    for(auto&& elem: vs)
        std::cout << elem << " ";
    std::cout << std::endl;
}

PS: there are more sophisticated approaches, like using custom char traits, but this does it and it's easy to understand. If you're really curios, can take a look here:

https://stackoverflow.com/a/5319855/3093378

2
Oncaphillis On
std::for_each(myWord.begin(),myWord.end(),[] (char &c) {c=std::tolower(c);});