gpt4 book ai didi

c - 如何接受并同时哑掉不需要的输入? (扫描)

转载 作者:太空宇宙 更新时间:2023-11-04 01:45:12 32 4
gpt4 key购买 nike

我在玩 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

从一个 ansser 编辑代码(测试代码以了解它是如何工作的)

#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;
}

最佳答案

I would like to read the whole input and then ignore the rest.

不要使用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.
}

关于c - 如何接受并同时哑掉不需要的输入? (扫描),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55033648/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com