Question: Why is my for loop not iterating for the third time?
What I noticed: In the for loop statement below, removing the if-else statement allowed me to print i from 0-2 and the "1" three times.
for (size_t i {0}; i < user_input.length(); ++i) {
cout << i << endl;
cout << user_input.length() << endl;
string the_spaces;
string the_line;
for (size_t b {i}; b < (user_input.length() - 1); ++b) {
the_spaces += " ";
}
for (size_t k {0}, y {i+1}; k < y; ++k) {
the_line += user_input[k];
}
if (i >= 1) {
cout << "Bob";
for (size_t z {i - 1}; z >= 0; --z) {
the_line += user_input[z];
}
}
else {
cout << "Beb" << endl;
}
cout << "1" << endl;
}
Output:
0 // i
3 // the user_input.length
Beb // output from if-else
1 // 1 printed at the end of the for loop expression
1 // i (2nd iteration)
3 // the user input.length
the code ends here… Neither printing Beb or Bob, as well as, the "1" from cout << "1" << endl; on the 2nd & 3rd iteration.
>Solution :
z >= 0 is always true since z is an unsigned type.
Your program therefore loops. Although there are other solutions, using a long long rather than a std::size_t as the loop index is probably the simplest.
b < (user_input.length() - 1) is also problematic if user_input is empty. Use
b + 1 < user_input.length()
instead.