0

I am attempting to print a string to the console with this code and I'm using subscript operators to change characters at specific indices, when I run my code this way, it prints an empty string several times.

    char last = 'c';
    string str = "";
    for (int i = 97; i <= (int)last; i++)
    {
        str[0] = (char)i;
        for (int j = 97; j <= (int)last; j++)
        {
            str[1] = (char)j;
            cout << str;
            cout << endl;
        }
    }

However, when I write my code this way, it prints out the characters I want to see.

char last = 'c';
string str;
for (int i = 97; i <= (int)last; i++)
{
    str[0] = (char)i;
    for (int j = 97; j <= (int)last; j++)
    {
        str[1] = (char)j;
        cout << str[0] << str[1];
        cout << endl;
    }
}

Is there anyway to get the characters I am manipulating to be saved into the string I initialized? Thank you!!

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • 2
    `str[0] = (char)i;` -- Change that to `str.at(0) = (char)i;` and watch what happens. The string is empty, thus there is no element `0`. – PaulMcKenzie Oct 26 '21 at 00:06
  • 1
    Unrelated: [Avoid magic numbers](https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad). If you go with `for (char i = 'a'; i <= last; i++)` your code will be easier to read and probably a bit more portable and robust. – user4581301 Oct 26 '21 at 00:11

1 Answers1

1

You are indexing into an empty std::string, which is undefined behavior.

If you want to use the string's operator[], you need to allocate space in the string first, eg:

char last = 'c';

string str(2, '\0'); // <-- HERE

// Alternatively:
//
// string str;
// str.resize(2);

for (char i = 'a'; i <= last; ++i)
{
    str[0] = i;
    for (char j = 'a'; j <= last; ++j)
    {
        str[1] = j;
        cout << str << endl;
    }
}

Otherwise, just use a plain char[] array instead, eg:

char last = 'c';
char str[3] = {};

for (char i = 'a'; i <= last; ++i)
{
    str[0] = i;
    for (char j = 'a'; j <= last; ++j)
    {
        str[1] = j;
        cout << str << endl;
    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770