【问题标题】:I don't understand why I can't get three inputs in c我不明白为什么我不能在 c 中获得三个输入
【发布时间】:2011-10-19 09:05:42
【问题描述】:

我的一个朋友正在尝试学习 c(她自己,用一本书),有时她会寻求帮助。

她只是向我展示了一些我无法回答的东西;我很惭愧,但我在大学学习了 C,然后转到了 php。我真的被困住了,所以我想知道为什么我们不能得到三个输入。这是部分代码:

#include <stdio.h>

int main()
{
    int num1;
    int num2;
    char x;

    printf("Enter a number:\n");
    scanf("%d\n",&num1);
    printf("Enter another number:\n");
    scanf("%d\n",&num2);
    printf("Choose an operation sign:\n");
    scanf("%c\n",&x);

...

像这样它会要求第一个输入两次,像这样:

Enter a number:
1
2
Enter another number:
3
Choose an operation sign:
-

如果我删除\n,它会跳过最后一个scanf

你能帮我理解为什么吗?

【问题讨论】:

  • 请注意,使用上面的示例输入,您会得到num1 == 1num2 == 2x == '3'
  • 如果删除\n,程序不会跳过最后一个scanf。相反,scanf 仍留在缓冲区中的 \n 被存储在变量 x 中。

标签: c scanf


【解决方案1】:

在这里阅读:scanf() leaves the new line char in buffer?

解决方案:

int main()
{
    int num1;
    int num2;
    char x;

    printf("Enter a number:\n");
    scanf("%d",&num1);
    printf("Enter another number:\n");
    scanf("%d",&num2);
    printf("Choose an operation sign:\n");
    scanf("\n%c",&x); /* See the \n <---------------- */
}

另一种选择:

char buf[2]; /* We need 2 characters for the null */
scanf("%1s", buf); /* We ask max 1 character (plus null given by scanf) */
char x = buf[0]; /* We take the first character */

作为一个小提示,感谢scanf 的工作方式,您可以直接在第一个“输入”中插入所有数据和各种scanf 的解决方案。所以你可以插入123 234 +,它会被正确地分成三个变量。

【讨论】:

  • 查看此问题以获取另一种确保在两次读取之间从标准输入刷新所有垃圾的方法:I am not able to flush stdin
  • @Daniel 最后没有“便携式”解决方案。甚至 C 常见问题解答也告诉了它并提出了替代方案 c-faq.com/stdio/stdinflush2.html
  • @xanatos 您列出的 C 常见问题解答页面有一个可移植的代码 sn-p 用于清除缓冲区:P
  • @Farhan 是的,你是对的,但我是从另一个 POV 看的。最后,它打破了“标准”scanf 工作,您可以在其中预设下一个值(因此,如果您输入了5 3,您将“填充”前两个 scanf 并且使用5 3 +,您将获得整个反向抛光操作)
【解决方案2】:

是的,scanf 不会删除换行符,你也不能刷新 stdin,那么这样怎么样:

int num1;
char nleater;
printf("Enter a number:\n");
scanf("%d%c", &num1, &nleater);

或者确实是这样:

printf("Enter number sign number: ");
scanf("%d %c %d",&num1,&x,&num2);
printf("%d %c %d", num1, x, num2);

【讨论】:

    【解决方案3】:

    您也可以尝试使用fflush,但这取决于库实现(stdio)。 可以在 here 找到它的 C 参考。

    稍后我会对此进行测试并更新我的帖子并说明它是否有效。

    【讨论】:

    • 在输入流上调用 fflush 会导致未定义的行为。
    • 取决于编译器,VC 清空输入流。当然,这是非常不便携的。
    • 不是在编译器上,而是在实际的库实现中(如参考中所述)。这意味着在更新库时行为可能会发生变化。但出于学习目的,您可以使用它,因为它不是您可能需要长期支持或可移植性的生产环境。
    猜你喜欢
    • 2013-11-06
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 2020-09-20
    • 1970-01-01
    • 2015-07-31
    • 1970-01-01
    相关资源
    最近更新 更多