我正在制作一個多功能命令列應用程式,其中用戶具有加密-解密字串、檢查字串回文和反轉字串等功能,并且我開始使用加密-解密功能撰寫我的整個代碼,但顯然它是沒有按預期作業,有時它會加密/解密字串,再次執行時相同的代碼會自行退出而不接受字串輸入!我什至插入了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!");
}
}
uj5u.com熱心網友回復:
最好和最便攜的清除方法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 it
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/363013.html
標籤:C
上一篇:查找分配是否可以輕松調整大小?
下一篇:試圖擺脫fgetswhile回圈
