Write your question here.
Hey everybody I have some code that is supposed to reverse the order of a word. My program crashes and says: Debug Assertion Failed Expression: string subscript out of range. This piece of code makes my program crash : newsentence[end]=sentence[start];
Can someone please give me a fix.
while (x<y)
{
newsentence[end]=sentence[start];
start++;
end--;
}
While loops repeat while true.
In the above, x will always be less than y, since x never increments or changes in the loop; error.
You may want to consider modifying x or y within the loop; or use end or start.
Example:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
usingnamespace std;
int main()
{
string newsentence,sentence="Hello world";
int start=0, end=sentence.size()-1;
while (start<=end)
newsentence+=sentence[end--];
cout<<newsentence<<'\n';
return 0;
}
dlrow olleH
Process returned 0 (0x0) execution time : 0.018 s
Press any key to continue.
Also, newsentence has not been assigned a value. Modifying characters that do no exist, may result in errors; the work around I provided was to concatenate characters.