C++ 为什么是c++;代码给出这样的输出? #包括 使用名称空间std; 字符串str; 字符串STR; int main(){ 对于(int I=0;I

C++ 为什么是c++;代码给出这样的输出? #包括 使用名称空间std; 字符串str; 字符串STR; int main(){ 对于(int I=0;I,c++,C++,您有未定义的行为 您声明的字符串为空,它们的索引将超出范围 相反,您应该使用member函数或.ohhh…,man,tnx…将字符附加到字符串中,而不是执行“str+=I+'0';“我正在执行”str[I]+=I+'0';“…现在它可以工作了…”。。。。 #include<bits/stdc++.h> using namespace std; string str ; string STR ; int main(){ for(int I=0;I<6;I++)

您有未定义的行为

您声明的字符串为空,它们的索引将超出范围


相反,您应该使用member函数或.

ohhh…,man,tnx…将字符附加到字符串中,而不是执行“str+=I+'0';“我正在执行”str[I]+=I+'0';“…现在它可以工作了…”。。。。
#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("%s\n",str.c_str()); /// abcdef
    printf("%s\n",STR.c_str()); /// abcdef

    return 0;
}
abcdef abcdef 012345 abcdef 012345 abcdef