Hm, the three answers here have been able to misuse the tolower .
Its argument must be a non-negative or special value of EOF , otherwise Undefined Behavior. If all you have is ASCII characters, then the codes will be non-negative, so in this special case it can be used directly. But if there is any character other than ASCII, as in the Norwegian "blåbærsyltetøy" (blueberry jam), then these codes are most likely negative, so you must use the unsigned argument char .
In addition, for this case, the locale C must be set to the appropriate locale.
For example, you can set it to the default user locale, which is indicated by an empty string as an argument to setlocale .
Example:
#include <iostream> #include <string> // std::string #include <ctype.h> // ::tolower #include <locale.h> // ::setlocale #include <stddef.h> // ::ptrdiff_t typedef unsigned char UChar; typedef ptrdiff_t Size; typedef Size Index; char toLowerCase( char c ) { return char( ::tolower( UChar( c ) ) ); // Cast to unsigned important. } std::string toLowerCase( std::string const& s ) { using namespace std; Size const n = s.length(); std::string result( n, '\0' ); for( Index i = 0; i < n; ++i ) { result[i] = toLowerCase( s[i] ); } return result; } int main() { using namespace std; setlocale( LC_ALL, "" ); // Setting locale important. cout << toLowerCase( "SARAH CONNER LIKES BLÅBÆRSYLTETØY" ) << endl; }
An example of using this with std::transform :
#include <iostream> #include <algorithm> // std::transform #include <functional> // std::ptr_fun #include <string> // std::string #include <ctype.h> // ::tolower #include <locale.h> // ::setlocale #include <stddef.h> // ::ptrdiff_t typedef unsigned char UChar; char toLowerCase( char c ) { return char( ::tolower( UChar( c ) ) ); // Cast to unsigned important. } std::string toLowerCase( std::string const& s ) { using namespace std; string result( s.length(), '\0' ); transform( s.begin(), s.end(), result.begin(), ptr_fun<char>( toLowerCase ) ); return result; } int main() { using namespace std; setlocale( LC_ALL, "" ); // Setting locale important. cout << toLowerCase( "SARAH CONNER LIKES BLÅBÆRSYLTETØY" ) << endl; }
For an example of using the C ++ level language standard instead of the C language standard, see Johannes answer.
Cheers and hth.,
Cheers and hth. - alf
source share