gpt4 book ai didi

c - c 中整数的输入验证

转载 作者:行者123 更新时间:2023-11-30 14:43:13 25 4
gpt4 key购买 nike

this answer 中所读:

num will always contain an integer because it's an int. The real problem with your code is that you don't check the scanf return value. scanf returns the number of successfully read items, so in this case it must return 1 for valid values. If not, an invalid integer value was entered and the num variable did probably not get changed (i.e. still has an arbitrary value because you didn't initialize it).

As of your comment, you only want to allow the user to enter an integer followed by the enter key. Unfortunately, this can't be simply achieved by scanf("%d\n"), but here's a trick to do it:

  int num;
char term;
if(scanf("%d%c", &num, &term) != 2 || term != '\n')
printf("failure\n");
else
printf("valid integer followed by enter key");

我看到这篇文章工作得很好,但它在 do-while 循环中不起作用。我需要从用户那里获取正确的输入,但是当首先执行循环时,它会连续打印失败而不从用户那里获取。

问题是什么?

最佳答案

问题是有问题的字符没有从输入缓冲区中清除。如果您想在错误发生后清除直到行的第一个结尾,您必须明确地执行此操作:

int num;
char term;
for (;;) {
if(scanf("%d%c", &num, &term) != 2 || term != '\n') {
printf("failure\n");
int c;
while (('\n' != (c=fgetc(stdin))) && (c != EOF)); // clear up to end of line
if (c == EOF) break; // do not read past EOF...
}
else {
printf("valid integer followed by enter key");
break;
}
}

关于c - c 中整数的输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54073157/

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