You are overly complicating things mixing strlen()
and char[]
and #include <string>
. You rely on initialization without ever affirmatively nul-terminating decmess
, you don't need strcmp()
to compare a single character.
It appears you wanted to do:
#define MAXC 1024 /* if you need a constant, #define one (or more) */
void decrypt(char *mess)
{
char decmess[MAXC] = "";
int i = 0, decmp = 0;
for (; mess[i]; i++)
if (mess[i] != '&')
decmess[decmp++] = mess[i];
decmess[decmp] = 0; /* affirmatively nul-terminate despite initialization */
std::cout << decmess << '\n';
}
(note: a C-string is nul-terminated there is no need to get the length before iterating over the characters it contains, just loop until you find the nul-character (ASCII 0). Also, main()
taking no arguments is just int main()
or int main(void)
)
As to why what you did didn't work, strcmp(&mess[i], "&")
compares &
with whatever is left in mess
starting at mess + i
so you never match '&'
alone. &mess[i]
is simply a pointer to the ith character in mess
and using strcmp
compares from that position to end of string with "&"
. (you can limit that with strncmp(&mess[i], "&", 1)
-- but that is superfluous for if (mess[i] == '&')
Adding your short main()
you would have:
#include <iostream>
#define MAXC 1024 /* if you need a constant, #define one (or more) */
void decrypt(char *mess)
{
char decmess[MAXC] = "";
int i = 0, decmp = 0;
for (; mess[i]; i++)
if (mess[i] != '&')
decmess[decmp++] = mess[i];
decmess[decmp] = 0; /* affirmatively nul-terminate despite initialization */
std::cout << decmess << '\n';
}
int main(void)
{
char encmess[MAXC] = "";
std::cout << "Enter message to decrypt" << '\n';
std::cin.getline(encmess, MAXC);
decrypt(encmess);
}
(note: see: Why is “using namespace std;” considered bad practice? and C++: “std::endl” vs “\n”)
Example Use/Output
$ ./bin/decmess
Enter message to decrypt
sg&shx&f
sgshxf
Let me know if you have further questions.