string字符串,无法正常输出

问题:tmp_tmp数组中用for循环遍历输出,可以正常输出,但是直接用cout输出时为空,并且用tmp_tmp.size()查看数组长度时显示为0。

代码:

char code() {
    return (char)rand() % 122 + 48;
}
void Get_Check_Code() {
    srand((unsigned)time(NULL));
    int tmp_i_i = 0;
    string tmp_tmp;
    while (1) {
        char str = code();
        if (((str >= '0' && str <= '9') || (str >= 'a' && str <= 'z') || (str >= 'A' && str <= 'Z'))) {
            tmp_tmp[tmp_i_i++] = str;
            cout << str;
        }
        if (tmp_i_i == 8) {
            break;
        }
    }
    cout<<endl<<tmp_tmp;
}

tmp_tmp[tmp_i_i++] = str;修改为tmp_tmp += str;

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>
using namespace std;

char code() {
    return (char)rand() % 122 + 48;
}

void Get_Check_Code() {
    srand((unsigned)time(NULL));
    string tmp_tmp;
    for (int i = 0; i < 8; i++) {
        char str = code();
        if (((str >= '0' && str <= '9') || (str >= 'a' && str <= 'z') || (str >= 'A' && str <= 'Z'))) {
            tmp_tmp += str;
            cout << str;
        }
    }
    cout << endl << tmp_tmp;
}

int main() {
    Get_Check_Code();
    return 0;
}