【发布时间】:2014-07-11 01:10:32
【问题描述】:
我有这个代码,我想知道为什么我的代码会跳过扫描...
#include <stdio.h>
char nombre[20];
int tipo;
int edad;
int dias;
int repetir=0;
int main()
{
while (repetir==0){
int error=0;
do{
printf("Diga su Nombre: ");
scanf("%19[^\n]", nombre);
printf("Diga el tipo de Sala: ");
scanf("%d", & tipo);
printf("Diga la edad del Paciente: ");
scanf("%d", & edad);
printf("Dias de Hospitalizacion: ");
scanf("%d", & dias);
if ((tipo>4) || (tipo<0) || (edad<0) || (dias <0) ){
printf("Eror al ingresar los datos");
} else {
error = 1;
}
}
while(error==0);
printf("¿Algun otro paciente? SI=0 NO=1");
scanf("%d", &repetir);
}
return(0);
}
这只是一个简单的代码,但是当我运行代码时会出现这样的情况:
Diga su Nombre: (Name with spaces)
Diga el Tipo de Sala (Integer Number)
Diga la edad del Paciente (Integer Number)
Dias de Hospitalizacion (Integer Number)
//Check For errors
¿Algun otro paciente? SI=0 NO=1 (Pressing 0 To repeat)
//Repeat
Diga su Nombre: Diga el Tipo de Sala
....
....
代码不再向我询问字符串数据,我真的不知道在这种情况下我必须做什么......非常感谢您的帮助!
更新
这是我尝试过的......但只是冻结
// .....
scanf("%d", & dias);
//Dont really know what to do here :S
int c; while ( (c = getchar()) == '\n' && c != EOF ) { }
if ((tipo>4) || (tipo<0) || (edad<0) || (dias <0) ){
【问题讨论】:
-
字符串的 scanf 被“跳过”,因为从扫描重复代码时起,stdin 流的缓冲区中仍有换行符。添加一个 getchar() 调用来解决这个问题。