我的代码在其他联机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.
1条答案
按热度按时间hyrbngr71#
string input;
是空的,所以input[i]
访问字符串超出了边界,这使您的程序具有 * 未定义的行为 *。您可以将其resize
到size
以使其工作-或者在输入您希望它具有的size
之后 * 创建具有正确大小的字符串。示例: