【发布时间】:2016-10-07 20:44:05
【问题描述】:
我正在尝试编写一个简单的二进制计算器来重新熟悉 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;
【问题讨论】:
-
使用 fgets 从键盘读取,使用 sscanf 从字符串中提取
-
strchr(valid_operator, ...)将不起作用,因为它的定义缺少\0终止符,这对于字符串操作至关重要。试试char valid_operator[] = "+-*/";因为你将它的大小限制为4数组中没有终止符。 -
char valid_operator[4] - 你没有分配空终止符?将其更改为 const char* valid_operator = "+-*/";
-
不测试 scanf 的返回值是在寻求惊喜。
-
无效输入
"t"停留在输入缓冲区中无论您使用scanf格式说明符scanf多少次。解决这个问题的最简单方法是输入带有fgets的字符串,然后当该字符串上的sscanf失败时,您可以轻松获得新的输入。