I've tried to look into various sites about my problem but I still can't understand what's wrong with the code.
Instead of getting the intended written string I'm getting a random 100-long number and char combination (that starts with the inputted string followed by the delimitator) that is equal to null.
#include <stdio.h>
#include <string.h>
int main()
{
char message[100], ans;
int key = 3;
printf("Enter a message:");
scanf("%s", message); //keeps on going until reaches 100 random characters and numbers
printf("Encrypt [E] or decrypt [D]?: ");
scanf("%s", &ans);
}
I've tried various methods online but none seem to be working.
EDIT: Even if I try a simple string program does not work
#include <stdio.h>
#include <string.h>
int main()
{
char message[100];
printf("Enter a message:");
scanf("%s", message);
printf("Encrypted message: %s", message[100]);
}
I'm giving the input through the dev c++ console.
EDIT2:
This the message input received by the program:
Note that the delimiter (the "\" after the word) does not actually do his job.
EDIT3: This is the whole code of the program
#include <stdio.h>
#include <string.h>
void decryptmessage(char message[], int key)
{
char ch;
int i;
for(i = 0; message[i] != '\0'; ++i){
ch = message[i];
if(ch >= 'a' && ch <= 'z'){
ch = ch - key;
if(ch < 'a'){
ch = ch + 'z' - 'a' + 1;
}
message[i] = ch;
}
else if(ch >= 'A' && ch <= 'Z'){
ch = ch - key;
if(ch < 'A'){
ch = ch + 'Z' - 'A' + 1;
}
message[i] = ch;
}
}
printf("Decrypted message: %s", message);
}
void encryptmessage(char message[], int key)
{
char ch;
int i;
for(i = 0; message[i] != '\0'; ++i){
ch = message[i];
if(ch >= 'a' && ch <= 'z'){
ch = ch + key;
if(ch > 'z'){
ch = ch - 'z' + 'a' - 1;
}
message[i] = ch;
}
else if(ch >= 'A' && ch <= 'Z'){
ch = ch + key;
if(ch > 'Z'){
ch = ch - 'Z' + 'A' - 1;
}
message[i] = ch;
}
}
printf("Encrypted message: %s", message);
}
int main()
{
char message[100], ans;
int key = 3;
printf("Enter a message:");
scanf("%s", message);
printf("Encrypt [E] or decrypt [D]?: ");
scanf("%c", &ans);
if (ans == 'E') //this has to be substituted by its numerical value
encryptmessage(message, key);
else if (ans == 'D') //same as line 78
decryptmessage(message, key);
else
printf("Goodbye.");
return 0;
}
Now while the message is working as intended, the char ans goes automatically to the value of 10, without letting me give it an input. I really can't tell why.