Flip Capitalization

Flip capitalization

Based on the difference in ASCII codes for lower and upper case letters: Make a program that takes a string input and flips the capitalization.

Example

EntryPoint
eNTRYpOINT

Hint

You have to include <iostream> and <string>.

Use getline to avoid running into problems getting inputs with spaces.

You can use the range-based loop to cycle through each char in the std::string to count it.

Answer

#include <iostream>
#include <string>

int main() {
    // Get user input
    std::cout << "Enter a string: ";
    std::string input;
    std::getline(std::cin, input);

    // Flip the capitalization
    for (char &ch : input) {
        if (ch >= 'a' && ch <= 'z') {
            ch -= 32; // Convert to uppercase
        } else if (ch >= 'A' && ch <= 'Z') {
            ch += 32; // Convert to lowercase
        }
    }

    // Output the modified string
    std::cout << input<< std::endl;
}

This program loops through the string with a refference to each char. The & symbol in char &ch shows that we are getting a refference to the character, not just creating a new variable with the value of the character. This means that changing the value of ch will reflect on the value contained in input.

This program can also be made by creating a new string and adding the flipped-case characters from input to it.

Functions like std::tolower, and std::toupper can be used to flip the case, but to show the relationship between the ASCII codes of characters and their char value, adding and subtracting 32 to flip the case has been chosen.

Questions