+ 3
Your code fails because of undefined behaviour.
When you access a character in the string, either for read or write purposes, via the [] operator, you should only do so if the position is within the size of the string. Otherwise, you access memory that isn't necessarily yours, which can have an effect ranging from "everything goes fine" to "test case failed" to "program crashes".
When you need to add a character, use push_back() or the += operator:
Alphabets.push_back(Encoded[i]);
Message += Alphabets[index];
Also, generally speaking, you try to do too much that the string class already handles. For example, you can query the length of a string at any time via length() or size() instead of running your own counters. Furthermore, the last loop does just the same as printing the string itself would have achieved.
+ 1
// try this code
for(long unsigned int i=0; i<Encoded.length(); i++)
if(isalpha(Encoded[i]) || isblank(Encoded[i]) ) Alphabets.push_back(Encoded[i]);
for(int i=Alphabets.length()-1; i>=0; i--) cout << Alphabets[i];
+ 1
Because it is undefined behaviour, the specific example will depend on things like your compiler and library. When using the app, any input that results in a final string size > 16 is sufficient to crash your program for me.
If you are curious as to why this happens, here is an excerpt that imitates how the string is implemented under the hood (simplified, of course):
https://code.sololearn.com/c0FAo2cpYaa9/?ref=app
Basically, short string optimization kicks in and the _data pointer is set to the local buffer upon construction of both `Alphabets` and `Message`. When writing more than 16 characters into the buffer, you leave `Alphabets` and start overwriting `Message`, which is arranged directly after `Alphabets` on the stack. Since the _data pointer is the first field, it is being overwritten first and no longer points to the local buffer. This alone might crash earlier upon dereferenciation, but is pretty much guaranteed to when the string is destructed, as you attempt to deallocate unallocated memory.
0
#include <iostream>
using namespace std;
int main() {
string msg ="";
getline(cin,msg);
int lenn = msg.length();
string outMsg;
for(int x =0;x<lenn;x++)
{
int dLenn = lenn - x-1 ;
if(isalpha(msg[dLenn]) || msg[dLenn]== ' ')
{
outMsg.push_back(msg[dLenn]);
}
}
cout<<outMsg;
return 0;
}
0
As I already said:
"Because it is undefined behaviour, the specific example will depend on things like your compiler and library. When using the app, any input that results in a final string size > 16 is sufficient to crash your program for me."
I.e. in the app any input with at least 17 letters + spaces:
thisisatestexample
Fun things are fun!
1a2very3long4input5string6
012surely34seventeen56letters789