程序在不允许输入的情况下跳过 fgets

Program is skipping fgets without allowing input

基本上如标题所说.. 当我的程序从控制台 运行 时,它会询问您是要加密还是解密.. 当我输入 e 或 E 时,它会创建一个新的空白行(直到我输入某种文本),然后同时显示 "enter the text" 和 "enter the key" 行..

因此,在控制台中它看起来像:

您想 (E)ncrypt 还是 (D)ecrypt? e

asdf jkl; <---- 随机用户输入让程序继续..

输入您要加密的文本:输入用于加密的密钥:(用户输入)

然后程序退出..

//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 而不是 waiting/allowing 用户输入任何答案.. 为什么?

来自http://www.cplusplus.com/reference/cstdio/fgets/

"Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first."

推测您在输入 E 或 D 后按了 Enter。您的 scanf() 不使用换行符,因此它保留在输入流中。 fgets() 看到换行符和 returns.

scanf(" %c", &answer); 在输入缓冲区中留下一个 newline,由 fgets 占用。 " %c" 中的前导 space 消耗 leading whitespace 但不消耗 trailing whitespace .

您可以使用 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;
}