Issue
Here's my code, it just reverses the sentence:
#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;
}
Compilation works fine, but when I try to run the program, this happens:
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.
Solution
Your reversedSentence
string is empty, so indexing into it invokes undefined behavior. Instead, you can use push_back
like this:
for (int i = sentence.length() - 1; i >= 0; i--)
{
reversedSentence.push_back(sentence[i]);
}
Also note that your loop condition needs to be modified. In case sentence
is empty, you should static_cast
the .length()
to an int
before subtracting by 1, like this:
for (int i = static_cast<int>(sentence.length()) - 1; i >= 0; i--)
{
reversedSentence.push_back(sentence[i]);
}
You could also just use an algorithm for this:
reversedSentence = sentence;
std::reverse(reversedSentence.begin(), reversedSentence.end());
This avoids complications when the sentence
string is empty.
Answered By - cigien