c++ - 在C++中,我遇到无法理解的编译器错误

标签 c++ gcc compiler-errors g++ mingw

这是我的代码,它只是颠倒了句子:

#include <iostream>
#include <string>   

using namespace std;

int main()
{
    string sentence;
    string reversedSentence;
    int i2 = 0;

    cout << "Type in a sentence..." << endl;
    getline(cin, sentence);

    for (int i = sentence.length() - 1; i < sentence.length(); i--)
    {
        reversedSentence[i2] = sentence[i];
        i2++;
    }

    cout << reversedSentence << endl;
}
编译工作正常,但是当我尝试运行程序时,会发生这种情况:
Type in a sentence...
[input]
/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.

最佳答案

您的reversedSentence字符串为空,因此对其进行索引会调用未定义的行为。相反,您可以像这样使用push_back:

for (int i = sentence.length() - 1; i >= 0; i--)
{
    reversedSentence.push_back(sentence[i]);
}
另请注意,您的循环条件需要修改。如果sentence为空,则应先将static_cast .length()编码为int,然后再减去1,如下所示:
for (int i = static_cast<int>(sentence.length()) - 1; i >= 0; i--)
{
    reversedSentence.push_back(sentence[i]);
}
您也可以为此使用算法:
reversedSentence = sentence;
std::reverse(reversedSentence.begin(), reversedSentence.end());
这样可以避免在sentence字符串为空时带来麻烦。

关于c++ - 在C++中,我遇到无法理解的编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62897928/

相关文章:

c++ - 从指针过渡到对象?

c - 升级 glibc - 它如何在没有发行版补丁的情况下工作

c - printf 和 gcc -O 选项更改返回值

python - 缩进错误-Python

c++ - 通过基类指针获取子类类型

c# - 为什么 C# 中的 Dispose 模式不像 C++ 中的 RAII 那样工作

.net - 使用 @Html.ActionLink() 时出错

Linux (玛吉亚) : make not found/usr/bin/make

c++ - 如何使用 Visual Studio 2008 将字符串映射到函数?

gcc - -rpath 和 -L 有什么区别?