Loops and Text

In this lesson, we'll look at iterating through text using loops in C++. Text (std::string) can be iterated in several ways in C++, because we can treat it as a sequence of characters.

Example: We want to go through each character in the word 'Test' and print it. We have several options:

// 1. Classic for loop
std::string word = "Test";
for(int i = 0; i < word.length(); i++) {
    std::cout << word[i] << std::endl;
}

// 2. Range-based for loop
for(char character : word) {
    std::cout << character << std::endl;
}

// 3. While loop
int i = 0;
while(i < word.length()) {
    std::cout << word[i] << std::endl;
    i++;
}

All these methods will print:

T
e
s
t

In C++, we can also use the at() method instead of square brackets for safer access to characters:

std::cout << word.at(i) << std::endl;

This method checks whether the index is not out of range of the string, and if it is, throws an exception instead of causing undefined behavior.

Instructions

Choose any method to iterate through the variable text and print each character on a new line.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

7/9

Loops and Text | Start Coder