Loops and Text
In the lesson on vectors, you saw that a std::string is a sequence of characters of type char: word[0] is its first character, and word.size() is the number of characters. That's why you can go through text with the same loops as through a vector. With an index:
std::string word = "Hello";
for (int i = 0; i < word.size(); i++) {
std::cout << word[i] << std::endl;
}Or with the range-based for, where the variable has the type char:
std::string word = "Hello";
for (char character : word) {
std::cout << character << std::endl;
}Both loops print:
H
e
l
l
oA space is a character too, so for "Hi there", the loop would run 8 times. And uppercase and lowercase letters are different characters: 'H' == 'h' is false.
To compare a character, write it in single quotes: character == 'l'. With double quotes, character == "l", you would compare a character with a text, and Clang reports error: comparison between pointer and integer ('char' and 'const char *').
Printing on one line. So far, the loops printed every value on its own line, because of std::endl. Without it, the next output continues on the same line. This loop prints a space after each character, and the line ends only once, after the loop:
std::string word = "Hello";
for (char character : word) {
std::cout << character << " ";
}
std::cout << std::endl;H e l l o The loop with an index can also go backwards: start at the last index, word.size() - 1, and count down to 0 with i--. You'll try that in the exercise.
Instructions
- 1
Go through
textwith a range-basedforloop and print each of its characters on its own line. - 2
Below that, print the text backwards, on one line. Go through it with a loop with an index that starts at the last index,
text.size() - 1, and counts down to0. In the loop, printtext[i]withoutstd::endl, and end the line withstd::endlafter the loop. The output isdesserts.