基本上正如标题所说..当我的程序从控制台运行时,它会询问您是否要加密或解密..当我输入e或E时,它会创建一个新的空行(直到我输入某种文本),然后同时显示“输入文本”和“输入 key ”行。
因此,在控制台中它看起来像:
您想要 (E) 加密还是 (D) 加密?
asdf jkl; <----随机用户输入让程序继续..
输入您要加密的文本:输入用于加密的 key :(用户输入)
然后程序退出..
//message to be encrypted
char text[250];
//word to use as the key
char key[50];
//stores the encrypted word
char encrypted[250];
char answer;
printf("Would you like to (E)ncrypt or (D)ecrypt? ");
scanf(" %c", &answer);
if(answer == 'e' || answer == 'E')
{
printf("Enter the text you want to encrypt : ");
fgets(text, 250, stdin);
printf("Enter a key to use for encryption : ");
fgets(key, 50, stdin);
printf("Encrypted text : ");
//code that encrypts the text here
}
那么问题是它完全跳过 fgets 并且不等待/允许用户输入任何答案......为什么?
最佳答案
行 scanf("%c", &answer);
在输入缓冲区中留下一个 换行符
,由 fgets
获取。 "%c"
中的前导空格占用前导 空格,但不占用尾随 空格。
您可以使用 scanf
中的 "%*c"
格式说明符来删除 newline
,它会读取 newline
但丢弃它。不需要提供 var 参数。
#include <stdio.h>
int main(void)
{
char answer;
char text[50] = {0};
scanf(" %c%*c", &answer);
fgets(text, sizeof text, stdin);
printf ("%c %s\n", answer, text);
return 0;
}
关于c - 程序正在跳过 fgets 且不允许输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35247514/