Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For Loop is not iterating for a third time? (C++)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading