逐字存储字符串并打印

aas*_*man 0 c++ string storage reverse

为什么这个程序不会反向打印出"你好"?当我取消注释循环内的行时,它可以工作.我想知道为什么没有存储字符串值的概念.谢谢!

#include<iostream>

using namespace std;

void reverse(string str) {
        int length = str.length();
        int x = length, i = 0;
        string newString;

        while(x >= 0) {
                newString[i] = str[x-1];
                //cout << newString[i];
                x--;
                i++;
        }

        cout << newString;
}

int main() {
        reverse("hello");

return 0;
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*odd 5

newString大小为0(使用默认构造函数构造),因此用newString[i] =... 结尾写入它会导致未定义的行为.使用.resize写进去之前调整字符串(使它足够大)