Uppercase, Lowercase and Digits
The library <cctype> (character types) has functions that work with a single character. Two of them switch a letter between uppercase and lowercase:
std::toupper(c)gives the uppercase letter:std::toupper('a')is'A'.std::tolower(c)gives the lowercase letter:std::tolower('Q')is'q'.
Any other character stays as it is: std::toupper('7') is '7'. The functions don't change the character you pass them. They return a new one, and you have to store it:
std::string name = "aria";
name[0] = std::toupper(name[0]);
std::cout << name << std::endl;
std::string shout = "watch out";
for (char& c : shout) {
c = std::toupper(c);
}
std::cout << shout << std::endl;This prints:
Aria
WATCH OUTTo change every character, the loop uses a reference, char& c, just like int& number in the lesson on references. A line with only std::toupper(name[0]); compiles, but the name stays aria, because the new character is thrown away.
And one trap: when you print the result straight away, you get a number.
std::cout << std::toupper('a') << std::endl;
char letter = std::toupper('a');
std::cout << letter << std::endl;This prints:
65
AThe functions return the code of the character as an int (65 is the code of 'A', as you saw in the previous exercise), and std::cout prints an int as a number. Store the result in a char, and it's a character again.
Other functions answer a question about a character, so you use them as conditions:
std::isupper(c): is it an uppercase letter?std::isalpha(c): is it a letter?std::isdigit(c): is it a digit, from'0'to'9'?
std::string code = "R2D2";
int digits = 0;
for (char c : code) {
if (std::isdigit(c)) {
digits++;
}
}
std::cout << "Digits: " << digits << std::endl;This prints:
Digits: 2All these functions know only the English alphabet, the letters without accents.
Instructions
- 1
A player typed their name with Caps Lock on. Fix it: change the first character of
nameto uppercase and all the others to lowercase, in a loop that starts at index 1. Then print the name:Name: Aria99. The digits stay as they are. The test also runs your program with other names. - 2
Below that, count the digits in the name with
std::isdigit()and printDigits: 2.