【发布时间】:2018-09-16 02:01:12
【问题描述】:
在我的 C 程序的这一部分中,Do-While 是无限的。我试图做一个
循环用于有人想键入字符串而不是数值的情况。
int main(){
int cnotas;
do{
printf("\nIngrese la Cantidad de Notas del Estudiante\n--------------------------------------------\n"); //asks for the number of grades that are going to be used in the average calculation
if(cnotas>=1){ //if statement to break the loop when the amount of grades is 1 or more
break;
}
}while(scanf("%d", &cnotas)==0 && cnotas<1); \\gets the cnotas value and checks if is valid
promedioe(cnotas);
system("pause");
}
更新了!
忘了说我想拒绝来自用户的非数字输入,所以程序不会崩溃。
【问题讨论】:
-
如果你终止输入流,scanf 将永远不会读取任何内容,它会永远循环。如果你输入一个数字,它应该退出
-
查看
if(cnotas>=1)。第一次执行时cnotas的值是多少? -
执行永远不会跳出循环,因为非数字字符留在输入缓冲区中,并且总是被 scanf 立即读取。输入无效时需要清空输入缓冲区。
标签: c infinite-loop do-while