如何获取并同时哑化不必要的输入? (scanf)

时间:2019-03-06 23:11:06

标签: c

我在玩scanf时遇到了一个小问题……更具体地说,我想阅读整个输入内容,然后忽略其余内容。让我告诉你我的意思:

#include <stdio.h>

int main(void)
{
    int number_of_iterations = 1;
    int circles = 0;

    scanf("%d", &number_of_iterations);
    unsigned int chr[number_of_iterations][8];

    while (number_of_iterations > circles) {
        scanf("%x", chr[circles]);
        circles++;
    }

    int circles2 = 0;
    while (circles2 < circles){
        printf("%x \n", chr[circles2]);
        circles2++;
    }

    return 0;
}

这将需要X的输入,但是如果我输入如下内容:

1 1CAAC

      28    EAAEB5
  F489AD95
  CAAC

   28    EAAEB5
F489AD95 F489AD95 EAAEB5
F489AD95 F489AD95

输入将占用1 1CAAC,但我希望其余部分可读但丢弃……有任何功能吗?

Dominiks-MacBook-Pro-2:testing stylez$ ./a.out
1 1CAAC

      28    EAAEB5
  F489AD95
  CAAC

   28    EAAEB5
F489AD95 F489AD95 EAAEB5
F489AD95 F489AD95e30ca8c0Dominiks-MacBook-Pro-2:testing stylez$ 
Dominiks-MacBook-Pro-2:testing stylez$       28    EAAEB5
bash: 28: command not found
Dominiks-MacBook-Pro-2:testing stylez$   F489AD95
bash: F489AD95: command not found
Dominiks-MacBook-Pro-2:testing stylez$   CAAC
bash: CAAC: command not found
Dominiks-MacBook-Pro-2:testing stylez$ 
Dominiks-MacBook-Pro-2:testing stylez$    28    EAAEB5
bash: 28: command not found
Dominiks-MacBook-Pro-2:testing stylez$ F489AD95 F489AD95 EAAEB5
bash: F489AD95: command not found

从一个分析器中编辑的代码(测试代码以了解其工作原理)

#include <stdio.h>

int consume_line(void) {
    int ch;
    while ((ch = fgetc(stdin)) != '\n') && ch != EOF) {
        ;
    }
    return ch;
}

int main(void)
{
    int number_of_iterations = 1;
    int circles = 0;

    int cnt;
    switch (scanf("%d", &number_of_iterations)) {
        case 1: consume_line(); break;
        case 0: consume_line(); /* Decide if code should re-try reading, etc. */ break;
        case EOF:
            printf("hello");// Decide what to do if End-Of-File or rare Low-Level-Input-Error occurred.
    }

    return 0;
}

1 个答案:

答案 0 :(得分:3)

  

我想阅读整个输入,然后忽略其余输入。

请勿使用scanf(),而是使用fgets()进行所有用户输入,然后使用sscanf(), strtol()等进行解析。

如果必须留在scanf()上,请测试其返回值并消耗其余行。

int consume_line(void) {
  int ch;
  while ((ch = fgetc(stdin)) != '\n'  && ch != EOF) {
    ;
  }
  return ch;
}


....
switch (scanf("%d", &number_of_iterations)) {
   case 1: consume_line(); break;
   case 0: consume_line(); /* Decide if code should re-try reading, etc. */ break;
   case EOF: // Decide what to do if End-Of-File or rare Low-Level-Input-Error occurred.
}