lundi 15 mars 2021

what is the difference between initializing a string outside the for loop and inside the for loop?

I have two code's here there are the same, The only difference that I am using in the first code a string initialized inside the for loop, In the other hand I am using a string initialized outside the for loop but still getting to different answer's

string initialized inside the for loop :

#include <iostream>
#include <string>
using namespace std;
int main() {
    for (int i = 0; i < 10; i++) {
        string  TheString = "******";
        
        if (i < 3 || i > 6)
            TheString+= "     ";
        else {
            TheString += "aaaaa";
        }
        cout << TheString << endl;
    }
    return 0;
}

the output is this shape :

******     
******     
******     
******aaaaa
******aaaaa
******aaaaa
******aaaaa
******     
******     
******     

string initialized outside the for loop :

#include <iostream>
#include <string>
using namespace std;
int main() {
    string  TheString = "******";
    
    for (int i = 0; i < 10; i++) {
        if (i < 3 || i > 6)
            TheString+= "     ";
        else {
            TheString += "aaaaa";
        }
        cout << TheString << endl;
    }   
    return 0;
} 

the output is this shape :

******     
******          
******               
******               aaaaa
******               aaaaaaaaaa
******               aaaaaaaaaaaaaaa
******               aaaaaaaaaaaaaaaaaaaa
******               aaaaaaaaaaaaaaaaaaaa
******               aaaaaaaaaaaaaaaaaaaa
******               aaaaaaaaaaaaaaaaaaaa

I am really confused about what is happening and thank you in advance.

Aucun commentaire:

Enregistrer un commentaire