Concept: The following code was developed to perform simple encryption/decryption on a TEXT(string) input by user(read using scanf), by XORing it with a KEY(integer number), input by user. The program should run infinitely until the user chooses to "exit".
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
/*Declaration of variables*/
char text[1000] = {0};
int i, len, tmp, KEY;
/*Infinite run beings*/
while(1)
{
/*Taking in TEXT*/
printf("\nEnter a text to Encrypt/Decrypt [Type EXIT to exit]: ");
scanf("%1000[^\n]s", text);
/*Managing exit*/
if(strcmpi(text, "exit") == 0)
{
printf("...Exiting Program");
getch();
exit(1);
}
/*Taking in KEY*/
printf("\nEnter KEY [Must be a number]: ");
scanf("%d", &KEY);
/*Encryption engine*/
len = strlen(text);
for(i = 0; i < len; i++)
text[i] ^= KEY; /*Encrypting TEXT by XORing it with KEY*/
/*Output*/
printf("\nEncrypted text is: %s\n", text);
}
/*End of infinite run*/
return 0;
}
Problem: The program runs fine for the very first input but is unable to take any further input for the TEXT after that, while still in loop - the code jumps over "/*Taking in TEXT*/" and directly moves to "/*Taking in KEY*/". I have substituted the "scanf("%1000[^\n]s", text);" with a "fgets(text, 1000, stdin);" and "gets(text);", but the same problem remains. I tried putting the "/*Taking in TEXT*/" mechanism in a different function, but the same problem prevailed. On a side note, I tried replacing "char text[1000] = {0};" with "char *text = malloc(sizeof(char) * 1000);"(and later used "free(text);" as well, along with it), but nothing improved.
Can anyone point out where am I making a mistake? I think the mistake is fundamental in nature, but I cannot locate it. Any sort of positive help will be appreciated. :)
Thanx a ton mate!! Things are working fine after using
1 2 3 4 5
while(1)
{
fflush(stdin);//this will flush you buffer.
// remaining program is as it is.
}
Don't know why but this function should have been covered in our second semester "Introduction to Computer Programming"? It looks like a very fundamental function. Anyway, thanks for making me aware. Also can you suggest me some really good books on learning C completely. Please note, I want anything other than K&R...the book is too dense for me for a first read...
http://cplusplus.com/reference/clibrary/cstdio/fflush/
if it was open for reading and the last operation was an input operation, the behavior depends on the specific library implementation. In some implementations this causes the input buffer to be cleared, but this is not standard behavior.