问题描述
基本上如标题所示..当从控制台运行我的程序时,它将询问您是否要加密或解密..当我输入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)ncrypt或(D)ecrypt? e
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
}
那么问题就在于,它完全跳过了fget,而没有等待/允许用户输入任何答案.为什么?
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);
将newline
留在输入缓冲区中,由fgets
占用. " %c"
中的前导空格使用前导空格,但不使用 trailing 空格.
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.
使用scanf
中的"%*c"
格式说明符可以删除newline
,该说明符读取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\n", answer, text);
return 0;
}
这篇关于程序正在跳过fgets而不允许输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!