程序在不允许输入的情况下跳过 fgets [英] Program is skipping fgets without allowing input
问题描述
基本上正如标题所说.. 当我的程序从控制台运行时,它会询问您是要加密还是解密.. 当我输入 e 或 E 时,它会创建一个新的空行(直到我输入了某种文本),然后同时显示输入文本"和输入密钥"行..
Basically as the title says.. When my program is run from the console, it'll ask if you'd like to encrypt or decrypt.. and when I input e or E, it creates a new blank line (until I input some kind of text), then shows the "enter the text" and "enter the key" lines all at once..
所以,在控制台中它看起来像:
So, in the console it would look something like:
您想要 (E) 加密还是 (D) 加密?
Would you like to (E)ncrypt or (D)ecrypt? e
asdf jkl;<---- 随机用户输入以使程序继续..
asdf jkl; <---- random user input to get the program to continue..
输入您要加密的文本:输入用于加密的密钥:(用户输入)
Enter the text you would like to encrypt : Enter a key to use for encryption : (user input)
然后程序退出..
//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 而不是等待/允许用户输入任何答案..为什么?
So the problem, then, is that it's skipping the fgets entirely and not waiting/allowing the user to input any answers.. why for?
推荐答案
行 scanf(" %c", &answer);
在fgets
获取的输入缓冲区." %c"
中的前导空格消耗前导 空格而不是尾随 空格.
The line scanf(" %c", &answer);
is leaving a newline
in the input buffer which is taken by fgets
. The leading space in " %c"
consumes leading whitespace but not trailing whitespace.
您可以使用 "%*c"
格式说明符去除 newline
在 scanf
中读取 newline
但丢弃它.无需提供 var 参数.
You can get rid of the newline
with the "%*c"
format specifier in scanf
which reads the newline
but discards it. No var argument needs to be supplied.
#include <stdio.h>
int main(void)
{
char answer;
char text[50] = {0};
scanf(" %c%*c", &answer);
fgets(text, sizeof text, stdin);
printf ("%c %s
", answer, text);
return 0;
}
这篇关于程序在不允许输入的情况下跳过 fgets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!