1

I'm trying to convert string to lower case, here is my program:

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main(){
    string a;
    getline(cin, a);
    transform(a.begin(), a.end(), a.begin(), ::tolower);
    cout << a;
}

When I build the program, I get the warning:

C4244 '=': conversion from 'int' to 'char', possible loss of data

I know tolower return int, but how can I change it to char, can someone help me with this? Thanks!

5
  • Wrap tolower inside a closure, returning a chat? Commented Jan 30, 2021 at 16:35
  • 4
    Use a lambda function. Commented Jan 30, 2021 at 16:35
  • 1
    Also, tolower should be inside std namespace, not global scope, that is the c function. Commented Jan 30, 2021 at 16:36
  • 3
    stackoverflow.com/questions/313970/… contains some very good answers to the question you didn't really ask, but might have wanted to ask. Commented Jan 30, 2021 at 16:39
  • Use #include <cctype>. Commented Jan 30, 2021 at 20:33

1 Answer 1

3

Your use of tolower has undefined behavior! The cppreference page on std::tolower tells you exactly what to do to fix it:

Like all other functions from <cctype>, the behavior of std::tolower is undefined if the argument's value is neither representable as unsigned char nor equal to EOF. To use these functions safely with plain chars (or signed chars), the argument should first be converted to unsigned char:

char my_tolower(char ch) {
     return static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
}

Similarly, they should not be directly used with standard algorithms when the iterator's value type is char or signed char. Instead, convert the value to unsigned char first:

std::string str_tolower(std::string s) {
    std::transform(s.begin(), s.end(), s.begin(), 
                // static_cast<int(*)(int)>(std::tolower)         // wrong
                // [](int c){ return std::tolower(c); }           // wrong
                // [](char c){ return std::tolower(c); }          // wrong
                   [](unsigned char c){ return std::tolower(c); } // correct
                  );
    return s;
}

So your code should look like this:

transform(a.begin(), a.end(), a.begin(), [](unsigned char c) { return std::tolower(c); });

As for your warning, it's due to the warning level you have set for your compiler. You get around it you can explicitly cast the result:

transform(a.begin(), a.end(), a.begin(), [](unsigned char c) {
    return static_cast<char>(std::tolower(c));
});
Sign up to request clarification or add additional context in comments.

Comments