我正在制作一个多功能的命令行应用程序,其中用户具有诸如加密-解密字符串、检查字符串回文和反转字符串等功能,并且我开始使用加密-解密功能编写我的整个代码,但显然它不能像预期的那样工作,有时它会加密/解密字符串,相同的代码在再次执行时不接受字符串输入就会退出!我甚至插入了fflush(stdin),但没有成功!
#include <stdio.h>
void encryptDecrypt();
// void checkPalindrome();
// void reverseWord();
void main()
{
int choice;
printf("\nWelcome to Jeel's multi-feature C App\n\n");
printf("1. Encrypt-Decrypt a word\t2. Check Palindrome\t3. Reverse a word\n\n");
printf("Enter a feature: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
fflush(stdin);
encryptDecrypt();
break;
case 2:
// checkPalindrome();
break;
case 3:
// reverseWord();
break;
default:
break;
}
}
void encryptDecrypt()
{
fflush(stdin);
char eOrD;
printf("\nWelcome to the World of Encryption & Decryption! We're so glad that you're here!\n\n");
printf("Enter 'e' if you want to encrypt a word or 'd' if you want to decrypt a word (e/d): ");
scanf("%c", &eOrD);
if (eOrD == 'e' || eOrD == 'E')
{
fflush(stdin);
char *word;
printf("\nGreat! Now enter a word to encrypt it: ");
fflush(stdin);
gets(word);
char *ptr = word;
for (int i = 0; i < sizeof(ptr); i++)
{
if (*ptr != '\0')
{
*ptr = *ptr + 7;
ptr++;
}
}
printf("\nEncrypted string is: %s, which is encrypted with the key: %d", word, 7);
}
else if (eOrD == 'd' || eOrD == 'D')
{
fflush(stdin);
char *deWord;
printf("\nGreat! Now enter a word to decrypt it: ");
gets(deWord);
char *dePtr = deWord;
for (int i = 0; i < sizeof(dePtr); i++)
{
if (*dePtr != '\0')
{
*dePtr = *dePtr - 7;
dePtr++;
}
}
printf("\nDecrypted string is: %s, which is decrypted with the key: %d\n", deWord, 7);
}
else
{
printf("Invalid input! Please try again!");
}
}发布于 2021-11-22 10:07:41
清除stdin的最佳和最便携的方法是使用以下代码:
void clearStream()
{
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
}同样,下面的内容也是不正确的,请创建一个数组而不是指针:
char *word;
gets(word); //word is a pointer, gets will not create a block of memory for ithttps://stackoverflow.com/questions/70063899
复制相似问题