程序正在跳过fgets而不允许输入
基本上如标题所示..当我的程序从控制台运行时,它会询问你是否要加密或解密..当我输入e或E时,它会创建一个新的空行(直到我输入一些那种文字),然后一次显示“输入文字”和“输入密钥”行。
因此,在控制台中它看起来像:
你想(E)ncrypt还是(D)ecrypt? Ë
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而不是等待/允许用户输入任何答案..为什么?
行scanf(" %c", &answer);
在输入缓冲区中留下一个由fgets
占用的newline
。 " %c"
前导空格占用前导空格但不占用空白。
您可以使用scanf
的"%*c"
格式说明newline
删除newline
,该格式说明newline
读取newline
但丢弃它。 不需要提供var参数。
#include 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; }
来自http://www.cplusplus.com/reference/cstdio/fgets/
“从流中读取字符并将它们作为C字符串存储到str中,直到读取(num-1)个字符或者到达换行符或文件结尾,以先发生者为准。”
大概是在输入E或D后按Enter键。您的scanf()不使用换行符,因此它保留在输入流中。 fgets()查看换行符并返回。