当我尝试在不调试代码的情况下运行时,一切都可以顺利运行,但是只要按下Y
,我就可以继续输入数字,它会终止(必须说我需要帮助)
int main() {
int a;
char c;
do {
puts("dwse mou enan arithmo: ");
scanf_s("%d", &a);
if (a > 0) {
if (a % 2 == 0)
printf("the number %d is even \n", a);
else
printf("the number %d is odd \n", a);
} else {
printf("the program won't run with negative numbers \n");
}
printf("if you want to proceed press y or Y :");
c = getchar();
getchar();
} while (c == 'y' || c == 'Y');
return 0;
}
答案 0 :(得分:1)
由getchar()
读取的字符是在数字后键入但未被scanf_s
使用的待处理换行符。
在读取下一个字符进行连续性测试之前,您应该消耗此待处理的换行符,这可以在scanf
中轻松完成,并在%c
转换规范前加一个空格:
#include <stdio.h>
int main() {
int a;
char c;
for (;;) {
printf("dwse mou enan arithmo: ");
if (scanf_s("%d", &a) != 1)
break;
if (a >= 0) {
if (a % 2 == 0)
printf("the number %d is even\n", a);
else
printf("the number %d is odd\n", a);
} else {
printf("the program does not accept negative numbers\n");
}
printf("if you want to proceed press y or Y: ");
if (scanf_s(" %c", &c) != 1 || (c != 'y' && c != 'Y'))
break;
}
return 0;
}