c++ 运行时间错误:处理字符串时VS代码中的“/home/基思/builds/mingw/gcc......”

vhmi4jdf  于 2023-01-22  发布在  其他
关注(0)|答案(1)|浏览(132)

我的代码在其他联机C++编译器中运行正常,但在VS代码中引发意外错误。请查找代码中的错误。
VS代码版本-1.74.3

代码:

#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.
hyrbngr7

hyrbngr71#

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, '\0'); // 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
    }
}

相关问题