November 2005
Beginner to intermediate
594 pages
16h 23m
English
You have a string that you want to convert to lower- or uppercase.
Use the toupper
and tolower functions in the <cctype> header
to convert characters to upper- or lowercase. Example 4-20 shows how to do it using these
functions. See the discussion for an alternative.
Example 4-20. Converting a string’s case
#include <iostream>
#include <string>
#include <cctype>
#include <cwctype>
#include <stdexcept>
using namespace std;
void toUpper(basic_string<char>& s) {
for (basic_string<char>::iterator p = s.begin();
p != s.end(); ++p) {
*p = toupper(*p); // toupper is for char
}
}
void toUpper(basic_string<wchar_t>& s) {
for (basic_string<wchar_t>::iterator p = s.begin();
p != s.end(); ++p) {
*p = towupper(*p); // towupper is for wchar_t
}
}
void toLower(basic_string<char>& s) {
for (basic_string<char>::iterator p = s.begin();
p != s.end(); ++p) {
*p = tolower(*p);
}
}
void toLower(basic_string<wchar_t>& s) {
for (basic_string<wchar_t>::iterator p = s.begin();
p != s.end(); ++p) {
*p = towlower(*p);
}
}
int main() {
string s = "shazam";
wstring ws = L"wham";
toUpper(s);
toUpper(ws);
cout << "s = " << s << endl;
wcout << "ws = " << ws << endl;
toLower(s);
toLower(ws);
cout << "s = " << s << endl;
wcout << "ws = " << ws << endl;
}This produces the following output:
s = SHAZAM ws = WHAM s = shazam ws = wham
One would think that the standard string class has a member function that converts the whole thing to upper- or ...