#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;
}
在 VS Code 中運行時,輸入字串后顯示以下錯誤:
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.
此代碼在其他在線 c 編譯器中運行正常,但未在 VS Code 中運行。我不知道問題是什么。請在這里找到問題。
uj5u.com熱心網友回復:
string input;是空input[i]的,因此越界訪問字串,這會使您的程式具有未定義的行為。您可以resize讓它size作業 - 或者在輸入您想要的內容后創建具有正確大小的字串。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
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/414218.html
標籤:
下一篇:VSCode將圖示添加到活動欄
