gpt4 book ai didi

c - 验证 C 中的输入

转载 作者:行者123 更新时间:2023-11-30 15:08:05 24 4
gpt4 key购买 nike

我正在尝试编写一个简单的二进制计算器来重新熟悉 C。出于某种原因,第一次输入验证工作正常,即使数字的第二次验证以几乎相同的方式编写,如果用户输入如果输入错误,while 循环就会无限循环,而不等待新的用户输入。这是代码,感谢您的帮助。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
char operator[20];
char valid_operator[4] = "+-*/";
printf("Enter operator: ");
scanf("%s", operator);
printf("You entered: %s\n", operator);
while(strchr(valid_operator, (int)operator[0]) == NULL) {
printf("%s is not a valid operator. Enter +, -, /, or *: ", operator);
scanf("%s", operator);
}

代码一直有效到这里。如果用户第一次输入错误的输入,下一部分将陷入无限循环。重新提示永远不会发生。

  int input1;
int input2;
printf("Enter the two inputs (separated by whitespace): ");
int num_ints = 1;
num_ints = scanf("%d %d", &input1, &input2);
printf("Input 1: %d. Input 2: %d.\n", input1, input2);
while(num_ints < 2){
printf("Invalid input. Enter two integers separated by whitespace: ");
num_ints = 0;
num_ints = scanf("%d %d", &input1, &input2);
printf("Input 1: %d. Input 2: %d.\n", input1, input2);
}
return 0;

最佳答案

无限循环而不等待新用户输入的原因是当scanf时无法读取请求格式的字符(在您的情况下为 %d)它不会前进文件指针,并且在循环的下一次迭代中它将尝试再次读取相同的错误字符.

这与 POSIX 一致:http://pubs.opengroup.org/onlinepubs/009695399/functions/fscanf.html

if the comparison shows that they are not equivalent, the directive shall fail, and the differing and subsequent bytes shall remain unread.

此外,从 man scanf 返回值:

...return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

所以,你最好结合fgetssscanf .

do {
char buf[BUFSZ];
printf("Enter the two inputs (separated by whitespace): ");
if(fgets(buf, BUFSZ, stdin) == NULL)
{
/* Error exit. */
break;
}
num_ints = sscanf(buf, "%d %d", &input1, &input2);
} while(num_ints != 2);

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

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