【问题标题】:How to flush stray characters from input [duplicate]如何从输入中清除杂散字符[重复]
【发布时间】:2015-04-18 00:13:32
【问题描述】:

如何处理杂散字符输入,如下面的代码 sn-p 所示

#include <stdio.h>


int main ()
{
    int i, j=0;
    while (j <3)
    {
        printf("\n Enter the number to be displayed ");
        scanf("%d",&i);
        printf("\n The number to be displayed is %d \n", i);
        j++;
    }
    return 0;
}

输出

philipa@hq1-up-swe-01{1436}: ./a.out
 Enter the number to be displayed 45/
 The number to be displayed is 45
 Enter the number to be displayed
 The number to be displayed is 45
 Enter the number to be displayed
 The number to be displayed is 45

这里 '/' 加错了。我想在它作为下一个循环的输入之前刷新这个'/'。我该如何处理这种情况?

【问题讨论】:

  • 请客气,对于短代码sn-ps,请正确缩进您的代码。
  • 我不清楚你在问什么。我用 45 测试了你的代码:ideone.com/RM3wvv 它不会在任何地方应用“/”
  • 是的,'/' 没有添加到输出中,但您也无法输入任何其他数字。要求输入 3 个数字时只取 45
  • fflush() 或者如果这没有帮助c-faq.com/stdio/stdinflush2.html ...
  • 这个问题在网站上有数百个重复...请在发布前做一些研究。

标签: c


【解决方案1】:

你可以使用一个单循环,

int c;
while((c=getchar()) != '\n' && c != EOF);

它将清除输入缓冲区。将其放在 scanf 之后。

while(1)
{ 
   switch(opt)
   {
    ...
    ...
    ...
   }
   while((c=getchar()) != '\n' && c != EOF); // It will clear the buffer before getting the next value.
}

【讨论】:

  • 我故意添加了循环来突出这个问题。我想知道是否有任何方法可以处理此异常。对链表执行操作时说 while (1) { printf("\n 1.Insert Operation "); printf("\n 2.显示操作"); . . . printf("\n 10.退出"); printf("\n 输入要对链表执行的操作\n"); scanf("%d", &i); if (i 10 || i != 0-9) { printf("\n 无效输入 !!!!!!!!!!!!!!!\n ");继续 ; }
  • 你必须在while循环中这样做?
  • c 应该是 int,而不是 char
  • @Karthikeyan.R.S 你能解释一下为什么'/'在循环中两次都导致问题吗?
  • 您正在使用 scanf 提及获取整数的输入。 '/' 是字符,因此 scanf 不会读取它。所以它保留在缓冲区中。每次 scanf 得到它都会来的值。所以每次scanf都会失败。它采用正确给出的第一个值,否则为垃圾值。
猜你喜欢
  • 2019-05-10
  • 2019-04-08
  • 2014-08-04
  • 1970-01-01
  • 2017-10-05
  • 2014-06-24
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
相关资源
最近更新 更多