Run time error: "/home/keith/builds/mingw/gcc........" in VS Code while working with strings

Run time error: "/home/keith/builds/mingw/gcc........" in VS Code while working with strings

此代码在其他在线 C++ 编译器中 运行 正确,但在 VS Code 中抛出意外错误。请指出我的代码中的问题。 (错误也附在下面)

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string input;
    int size;
    cout << "Enter the size of your string value" << endl;
    cin >> size;
    cout << "Enter the string whose first letter has to be changed" << endl;

    for (int i = 0; i < size; i++)
    {
        cin >> input[i];
    }

    input[0] = 'Z';
    cout<<"The changed string is ";

    for (int i = 0; i < size; i++)
    {
        cout << input[i];
    }

    return 0;
}

错误:

Enter the size of your string value
4
Enter a string whose first letter has to be changed
moya
/home/keith/builds/mingw/gcc-9.2.0-mingw32-cross-native/mingw32/libstdc++- 
v3/include/bits/basic_string.h:1067: std::__cxx11::basic_string<_CharT, _Traits, 
_Alloc>::reference std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::operator[] 
(std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type) [with _CharT = char; 
_Traits = std::char_traits<char>; _Alloc = std::allocator<char>; 
std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::reference = char&; 
std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::size_type = unsigned int]: 
Assertion '__pos <= size()' failed.

string input; 为空,因此 input[i] 越界访问字符串,这使您的程序具有 未定义的行为 。您可以 resizesize 使其工作 - 或者在 输入您想要的 size 之后创建具有正确大小的字符串 它有。

示例:

#include <iostream>
#include <string>

int main() {
    std::string input;
    int size;
    std::cout << "Enter the size of your string value\n";
    if(std::cin >> size && size > 0) {

        input.resize(size); // resize the string
        // std::string input(size, '[=10=]'); // or create it here with the correct size

        std::cout << "Enter the string whose first letter has to be changed\n";

        for(char& ch : input) { // a simpler range-based for loop
            std::cin >> ch;
        }
        input[0] = 'Z';
        std::cout << "The changed string is ";
        std::cout << input << '\n'; // no need to loop here
    }
}