【问题标题】:Program is skipping fgets without allowing input程序在不允许输入的情况下跳过 fgets
【发布时间】:2016-02-06 22:55:58
【问题描述】:

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

所以,在控制台中它看起来像:

您想要 (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 而不是等待/允许用户输入任何答案.. 为什么?

【问题讨论】:

  • scanf(" %c", &answer); 在输入缓冲区中留下了一个newline,由fgets 占用:摆脱它。
  • @Weather Vane 这很有意义(抱歉,第一周学习 c)。你如何摆脱输入缓冲区中留下的换行符??

标签: c input io scanf fgets


【解决方案1】:

scanf(" %c", &answer); 行在输入缓冲区中留下newline,由fgets 占用。 " %c" 中的前导空格使用 leading 空格,但不使用 trailing 空格。

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

【讨论】:

  • 这很完美,写得很好/理解得很好。感谢您的时间和帮助!
  • 用我的完整代码对其进行了测试,它运行良好。再次感谢您!
【解决方案2】:

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

“从流中读取字符并将它们作为 C 字符串存储到 str 中,直到读取 (num-1) 个字符或到达换行符或文件结尾,以先发生者为准。”

大概您在输入 E 或 D 后按 Enter 键。您的 scanf() 不会使用换行符,因此它会保留在输入流中。 fgets() 看到换行符并返回。

【讨论】:

  • scanf 不使用换行符有什么特殊的逻辑原因吗?
  • 这会被 fflush(stdin) 修复吗?
  • @tom fflush(stdin) 不是标准的。 " %c" 中的前导空格使用 leading 空格,但不使用 trailing 空格。
  • @Wheezil 感谢您的回复 - 这很有道理。
猜你喜欢
  • 2011-04-13
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多