Working with Characters

The <cctype> library has small functions to test and change one char:

FunctionQuestion / job
isalpha(c)is it a letter?
isdigit(c)is it a digit 0–9?
isspace(c)is it a space (or tab, new line)?
isupper(c) / islower(c)is it a capital / small letter?
toupper(c) / tolower(c)the capital / small version
#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main() {
    string password = "Secret42";
    int letters = 0, digits = 0, capitals = 0;
    for (char c : password) {
        if (isalpha(c)) letters++;
        if (isdigit(c)) digits++;
        if (isupper(c)) capitals++;
    }
    cout << letters << " letters, " << digits << " digits, " << capitals << " capital\n";
    return 0;
}

Output

6 letters, 2 digits, 1 capital

Making text upper or lower case

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

int main() {
    string name = "Grace Hopper";
    string loud = name;
    for (char& c : loud) {
        c = toupper(c);
    }
    cout << loud << "\n";
    return 0;
}

Output

GRACE HOPPER

Characters are really numbers

Every char is stored as a number (its ASCII code). 'A' is 65, 'B' is 66, and so on. That's why you can do maths with characters:

#include <iostream>
using namespace std;

int main() {
    char letter = 'A';
    cout << static_cast<int>(letter) << "\n";      // 65
    char next = letter + 1;
    cout << next << "\n";                          // B
    char digit = '7';
    int value = digit - '0';                       // turn the char '7' into the number 7
    cout << value * 2 << "\n";
    return 0;
}

Output

65
B
14

Tip: c - '0' is a classic trick for turning a digit character into its number.

HOME LABS COMMUNITY DASHBOARD