为什么这个c++代码给出了这样的输出

why this c++ code gives such output?

本文关键字:输出 c++ 代码 为什么      更新时间:2023-10-16
#include<bits/stdc++.h>
using namespace std;
string str ;
string STR ;
int main(){
    for(int I=0;I<6;I++)    /// 012345
        str[I] = I + '0'  ;
    for(int J=0;J<6;J++)    /// abcdef
        STR[J] = J + 'a' ;
    cout << str << "  " << STR << endl ; /// blank line !!!

    printf("%sn",str.c_str()); /// abcdef
    printf("%sn",STR.c_str()); /// abcdef
    return 0;
}

输出::

<>之前六边形abcdef六边形abcdef之前

I expect::

<>之前012345年六边形abcdef012345六边形abcdef

您有未定义行为!

您声明的字符串为空,对它们的索引将越界。

相反,您应该字符附加到字符串中,使用append成员函数或+=操作符。