Search code examples
c++stringcoutxor

String is not being printed after Assign it in a Loop C++


I don't know why I cannot print my string after I assign each index to a value in the loop. I can print it each index in the loop, but I cannot print the string using only cout<

#include <iostream>

using namespace std;

int main()
{
    //EXPECTED OUTPUT : 000010110010000

    string string1 = "011011110011000";
    string string2 = "011001000001000";
    string final_key;

    for(int i = 0; i<15; i++) //XOR
     {
        final_key[i] = ((string1[i]-'0') ^ (string2[i]-'0')) + '0';
        cout<<final_key[i]; //it prints correctly.
     }

     cout<<final_key; //it doesnt print anything at all :(
    return 0;
}

Solution

  • The issue is that you have an out-of-bounds access in the final_key string here:

    final_key[i] = ((string1[i]-'0') ^ (string2[i]-'0')) + '0';

    Since final_key starts out as an empty string, you either have to size it appropriately before accessing the ith entry, or you concatenate onto the empty string:

    So it's either this:

    final_key.resize(15);
    for (int i = 0; i < 15; ++i )
        final_key[i] = ((string1[i]-'0') ^ (string2[i]-'0')) + '0';
    

    or this:

    for (int i = 0; i < 15; ++i )
        final_key += ((string1[i]-'0') ^ (string2[i]-'0')) + '0';
    

    or this:

    for (int i = 0; i < 15; ++i )
        final_key.push_back(((string1[i]-'0') ^ (string2[i]-'0')) + '0');
    

    Note:

    To show that you are going out-of-bounds, in your original code (with no resize(15) fix), replace this:

    final_key[i] = ((string1[i]-'0') ^ (string2[i]-'0')) + '0';

    with this:

    final_key.at(i) = ((string1[i]-'0') ^ (string2[i]-'0')) + '0';

    You should get a std::out_of_range exception thrown, showing you that the i'th entry is out-of-bounds.