#include <stdio.h> #include <string.h> #include <malloc.h> #define CRYPT_OK 1 #define CRYPT_ERROR 0 en
Um crypt_type {ENCRYPT, DECRYPT};
int i,k;
Char sequencebuf[1024];
char * sequencesrc = NULL;
char * sequencedst = NULL;
int length;
int Encrypt () {printf ("Please input your sourcestring:\n"); Fflush (stdin);
Empty the input buffer fgets (sequencebuf, sizeof (SEQUENCEBUF), stdin);
printf ("Please input your keynum:\n");
scanf ("%d", &k);
Length = strlen (SEQUENCEBUF);
SEQUENCESRC = (char *) malloc (length * sizeof (char));
for (i = 0; i < length-1 i++) sequencesrc[i] = Sequencebuf[i]; Sequencesrc[length-1] = ' the ';
string Terminator SEQUENCEDST = (char *) malloc (length * sizeof (char));
for (i = 0; i < length-1 i++) sequencedst[i]= ' a ' + (sequencesrc[i]-' a ' + K)%26;
Sequencedst[length-1]= ' ";
return CRYPT_OK;
int decrypt () {printf ("Please input your sourcestring:\n");
Fflush (stdin);
Fgets (sequencebuf, sizeof (SEQUENCEBUF), stdin); printf ("PleaseInput your keynum:\n ");
scanf ("%d", &k);
Length = strlen (SEQUENCEBUF);
SEQUENCESRC = (char *) malloc (length * sizeof (char));
for (i = 0; i < length-1 i++) sequencesrc[i] = Sequencebuf[i];
Sequencesrc[length-1] = ' the ';
SEQUENCEDST = (char *) malloc (length * sizeof (char));
for (i = 0; i < length-1 i++) {sequencedst[i]= ' a ' + (sequencesrc[i]-' a ' + 26-k)%26;
} sequencedst[length-1]= ';
return CRYPT_OK;
int main () {int choice =-1;
int result = 0;
printf ("Encrypt:please input 0\ndecrypt:please input 1\nplease choose:");
scanf ("%d", &choice);
Switch (choice) {Case encrypt:result = ENCRYPT ();
Break
Case decrypt:result = DECRYPT ();
Break
default:printf ("input illegal \ n");
Break
} if (Result) {printf ("sequencesrc:%s\n", SEQUENCESRC);
printf ("sequencedst:%s\n", SEQUENCEDST);
return 0;
}
In the cryptographic decryption function, Fflush (stdin) was executed before calling the Fgets function, which was to empty the input buffer.
When data is continuously read from the console, a buffer that is not used by the data entered in the previous phase affects the reception of the next stage.
In this example, the main function scanf function receives an integral type, and when the carriage return represents the end, the integer is choice received, but the carriage return line feed is also in the buffer. The Fgets function is just the end of a newline character, so when you enter a child function, the statement is quickly forced to execute without emptying the buffer. Reaction to the console, it seems that the statement is not executed, so you need to fflush empty the buffer.