나는 몇 가지 이유 때문에 첫 번째 입력 확인이 잘 작동하는 간단한 바이너리 계산기를 작성하려고합니다. 숫자에 대한 두 번째 확인이 거의 같은 방식으로 작성되었지만, 사용자가 잘못된 입력을 입력하면 while 루프는 새로운 사용자 입력을 기다리지 않고 무한 루프를 반복합니다. 여기에 코드가 있으며 도움을 주셔서 감사합니다.C에서 입력 확인
#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는 (... valid_operator)', 작동하지 않습니다, 키보드에서 읽은 문자열 –
'strchr과에서 추출 sscanf를를 사용하는에 대해 그 정의가 없기 때문에 그것은'\ 내기 문자열 조작에 필수적인 '0'터미네이터입니다. 'char valid_operator [] = "+ - * /";'크기를'4 '로 제한 했으므로 배열에 터미네이터가 없습니다. –